2015-05-13 42 views
0

BtnNext_Click方法,它只是從文本文件閱讀,就像是一個不同的文本文件,而不是從已經被打開了一個同一個文本文件。它不會逐行進行。 我需要幫助閱讀不同方法

下面是代碼:

public void ScrubData() 
{   
    string FileName1; 
    string FilePath1; 

    // Display an OpenFile Dialog box for user 
    OpenFileDialog openFileDialog1 = new OpenFileDialog(); 
    openFileDialog1.Filter = "txt Files|*.txt"; 
    openFileDialog1.Title = "Select a txt File"; 

    // Show the Dialog. If user clicked OK in the dialog 
    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
    { 
     try 
     { 
      String strFileName = openFileDialog1.FileName; 
      String strFilePath = System.IO.Path.GetDirectoryName(strFileName); 
      String fileName = System.IO.Path.GetFileNameWithoutExtension(strFileName); 
      String strFileNameAndPathNew = strFilePath + 
       openFileDialog1.InitialDirectory + "\\" + fileName + "_scrubbed.txt"; 

      // If scrubbed file exists, delete it first 
      if (System.IO.File.Exists(strFileNameAndPathNew)) 
      { 
       System.IO.File.Delete(strFileNameAndPathNew); 
      } // End IF 
      if (System.IO.File.Exists(strFileName)) 
      { 
       int lineCount = System.IO.File.ReadAllLines(strFileName).Length; 
       System.IO.StreamReader file = new System.IO.StreamReader(strFileName); 
       // Status label 
       LblStatus.Text = "File Loaded Successfully"; 
       LblStatus.Visible = true; 
       string line; 
       while ((line = file.ReadLine()) != null) 
       { 
        const char DELIM = '|'; 
        // MessageBox.Show(line); 

        string[] word = line.Split(DELIM); 
        Txt2NormAccNum.Text = word[3]; 
        //string accScrubbed = ReplaceData(word[0],"SSN"); 
        Txt3NormAmnt.Text = word[4]; 
        Txt4NormFirstNam.Text = word[1]; 
        Txt5NormLastNam.Text = word[2]; 
        Txt6NormSS.Text = word[0]; 
        Txt7NormItem.Text = word[5]; 
       } // End WHILE 
      } // End IF 
      else 
      { 
       // Status label 
       LblStatus.Text = "File Load Failed!"; 
       LblStatus.Visible = true; 
      } // End ELSE 
      // Text box one code: 
      FileName1 = openFileDialog1.FileName; 
      Txt1.Text = FileName1; 
      // 
     } // End TRY 
     catch (Exception e1) 
     { 
      if (e1.Source != null) 
      { 
       Console.WriteLine("IOException source: {0}", e1.Source); 
       throw; 
      } // End IF 
     } // End CATCH 
    } // End IF 
} // End Scrub Method 

我需要重複使用的變量,如在我的下一個方法「strFileName」。

我通過在文本文件中的每一行創建一個以前&下一個按鈕循環:

public void BtnNext_Click(object sender, EventArgs e) 
{ 
    StreamReader myReader2 = new StreamReader("colin.txt"); 
    string line2 = ""; 

    while (line2 != null) 
    { 
     line2 = myReader2.ReadLine(); 
     if (line2 != null) 
     { 
      const char DELIM = '|'; 
      // MessageBox.Show(line); 
      string[] word = line2.Split(DELIM); 
      Txt2NormAccNum.Text = word[3]; 
      Txt3NormAmnt.Text = word[4]; 
      Txt4NormFirstNam.Text = word[1]; 
      Txt5NormLastNam.Text = word[2]; 
      Txt6NormSS.Text = word[0]; 
      Txt7NormItem.Text = word[5]; 

      //Txt12ScrubSS.Text; 
      //Txt10ScrubFirstNam.Text; 
      //Txt11ScrubLastNam.Text; 
      //Txt8ScrubAcctNum.Text; 
      //Txt9ScrubAmt.Text; 
      //Txt13ScrubItem.Text; 
     } 
    } 
    myReader2.Close(); 

} // end method 

如果你看到什麼即時消息說:該設計是:用戶打開文件,從文件中的文本的第一行顯示在窗體上,然後我有一個'上一個'和'下一個'按鈕,我想通過同一個文件中的文本行來循環。

@Tim是啊我想我知道你在說什麼在這裏看看這個:

using System; 
    using System.Collections.Generic; 
    using System.ComponentModel; 
    using System.Data; 
    using System.Drawing; 
    using System.Linq; 
    using System.Text; 
    using System.Threading.Tasks; 
    using System.Windows.Forms; 
    using System.IO; 

    namespace Project2_DataScrubber 
    { 
public partial class Form1 : Form 
{ // Begin Class #1 

    public Form1() 
    { // Begin Main Method 


     InitializeComponent(); 

     // MessageBox.Show(GetRandomNumbers().ToString()); 


    } // End Main Method 

    private void Btn4_Click(object sender, EventArgs e) 
    { // Btn4 CLICK Method 

     // Closes Form 1 
     this.Close(); 
    } // End Method 

    private void Btn3_Click(object sender, EventArgs e) 
    { // Btn3 CLICK Method 

     // Display alert message box of are you sure you want to reset the data 
     DialogResult dialogResult1 = MessageBox.Show("Are you want to reset the data?", "ALERT", MessageBoxButtons.YesNo); 
     if (dialogResult1 == DialogResult.Yes) 
     { 
      // Resets all the data, textboxes, ect 
      Txt1.Text = "No file loaded."; 
      Txt2NormAccNum.Clear(); 
      Txt3NormAmnt.Clear(); 
      Txt4NormFirstNam.Clear(); 
      Txt5NormLastNam.Clear(); 
      Txt6NormSS.Clear(); 
      Txt7NormItem.Clear(); 
      Txt8ScrubAcctNum.Clear(); 
      Txt9ScrubAmt.Clear(); 
      Txt10ScrubFirstNam.Clear(); 
      Txt11ScrubLastNam.Clear(); 
      Txt12ScrubSS.Clear(); 
      Txt13ScrubItem.Clear(); 
      Txt14ScrubYesNo.Clear(); 
      LblStatus.Visible = false; 
     } 
     else if (dialogResult1 == DialogResult.No) 
     { 
      // Do nothing 
     } 

    } // End Method 

    public void Btn1_Click(object sender, EventArgs e) 
    { // Btn1 CLICK Method 

     ScrubData(); 
    } // End Method 

    public void Btn2_Click (object sender, EventArgs e) 
    { 
     if (Txt2NormAccNum.Text != "" || Txt3NormAmnt.Text != "" || Txt4NormFirstNam.Text != "" || Txt5NormLastNam.Text != "" || 
      Txt6NormSS.Text != "" || Txt7NormItem.Text != "") 
     { 
                   // 
      Txt12ScrubSS.Text = GetRandomNumbers().ToString(); // Replace SS textbox 
      // 
      #region 
      int lastNameLetters = Txt5NormLastNam.Text.Length; // 
      string lettersTwo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
      Random randLetters = new Random(); 
      string randomString = ""; 
      for (int i = 0; i < lastNameLetters; i++) 
      {             // Replace Last Name 
       randomString += lettersTwo 
        [randLetters.Next(0, 25)].ToString(); 
      } 
      Txt11ScrubLastNam.Text = randomString;    // 
      #endregion 
      #region 
      var newAccountNum = "";        // 
      int numOfCharacters = 4; // # to leave behind 
      for (var i = 0; i<Txt2NormAccNum.Text.Length - numOfCharacters; i++) 
      { 
       newAccountNum += "X";       // Replace Account Number 
      } 
      newAccountNum += Txt2NormAccNum.Text.Substring 
       (Txt2NormAccNum.Text.Length - numOfCharacters); 
      Txt8ScrubAcctNum.Text = newAccountNum;    // 
      #endregion 
      #region 
      double moneyAmountDoub = 0;       // 
      string moneyAmountStr = ""; 
      moneyAmountStr = Txt3NormAmnt.Text; 
      moneyAmountDoub = Convert.ToDouble(moneyAmountStr); 
      if (moneyAmountDoub > 100.00) 
      {             // Get Yes or No answer 
       Txt14ScrubYesNo.Text = "Yes";    
      } 
      else 
      { 
       Txt14ScrubYesNo.Text = "No"; 
      }             // 
      #endregion 

      Txt10ScrubFirstNam.Text = Txt4NormFirstNam.Text; 
      Txt13ScrubItem.Text = Txt7NormItem.Text; 
      Txt13ScrubItem.Text = Txt7NormItem.Text; 
      Txt9ScrubAmt.Text = Txt3NormAmnt.Text; 




     } 
     else 
     { 
      MessageBox.Show("Error: Information missing from the Data section"); 
     } 
    } 

    public void ScrubData() 
    { // Begin Scrub Method 
+1

我真的不知道問題是什麼,但是整個'XXX'/'XXX結尾'確實會降低您的代碼可讀性。 –

+1

根據你發佈的內容,很難說出你有什麼問題(如果有的話)。什麼是預期的行爲與發生了什麼?你是什​​麼意思,它看起來像在閱讀,就像它是一個不同的文件?您需要使用類字段(或屬性)來存儲文件路徑,以便您可以在不同的方法中重用它。 – JNYRanger

+0

我想要一個動態文件名不只是像「bob.txt」那樣的靜態 – Colin

回答

0

有幾件事情你需要做。首先,您需要創建類級別變量(更適當地稱爲字段)來保存需要通過不同方法訪問的信息。

其次,您需要跟蹤文件中的哪個位置(什麼行),因爲每次創建StreamReader時,它都會將讀取器放在第一行。正如RogueBukkitDev所說,作爲一個推論,您應該讀一次該文件並將其轉儲到List<string>或數組(string[])中。然後,您將根據用戶的方向 - 前進或後退增加或減少集合中的當前位置。

它可能是這個樣子:

public partial class Form1 : Form 
{ 

    // Class level fields 
    private string fileName = String.Empty; 
    private string[] fileLines; 
    private int currentLine = 0; 
    const char DELIM = '|'; 

    public void ScrubData() 
    {   

     // Display an OpenFile Dialog box for user 
     OpenFileDialog openFileDialog1 = new OpenFileDialog(); 
     openFileDialog1.Filter = "txt Files|*.txt"; 
     openFileDialog1.Title = "Select a txt File"; 

     // Show the Dialog. If user clicked OK in the dialog 
     if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     { 
      try 
      { 
       fileName = openFileDialog1.FileName; 
       newFileName = String.Format(@"{0}\{1}_scrubed.txt", 
          openFileDialog1.InitialDirectory, 
          Path.GetFileNameWithoutExtension(fileName)); 
       fileLines = File.ReadAllLines(fileName); 
       currentLine = 0; 
      } 
     } 
    } 

    public void BtnNext_Click(object sender, EventArgs e) 
    { 

     if (currentLine <= fileLines.Length) 
     { 
      string line2 = fileLines[currentLine]; 
      string[] word = line2.Split(DELIM); 

      Txt2NormAccNum.Text = word[3]; 
      Txt3NormAmnt.Text = word[4]; 
      Txt4NormFirstNam.Text = word[1]; 
      Txt5NormLastNam.Text = word[2]; 
      Txt6NormSS.Text = word[0]; 
      Txt7NormItem.Text = word[5]; 

      currentLine = currentLine + 1; 
     } 
    } 
} 

很多的變化在這裏,我ommitted代碼,這是不相關的例子。

首先,我聲明4個字段 - 一個用於文件名,一個用於洗滌的文件名,一個用於該文件的當前行,而對於一個定界符恆定。

接着,在ScrubData方法是該文件是由用戶選擇的,它只是簡單地調用File.ReadAllLines(),這將返回一個字符串數組(每行一個數組元素),並且將其存儲在類級字段fileLines。它還將currentLine設置爲0,以防用戶在退出程序之前選擇不同的文件。

btnNext_Click事件處理程序,它讀取線陣列(fileLines)當前行 - 確保你不會有一個索引出界失誤後,再分割他們的分隔符,並填充文本框。然後它將currentLine增加1。

要回去,它將基本上是相同的邏輯,除了你會減少currentLine由1(並檢查,以確保你不會超過0)。

這是我們一直試圖解釋的基本輪廓。您可能需要對其進行修改以適應您的實際需求,但原則保持不變。

+0

謝謝這麼多! – Colin

+0

@Colin - 不客氣。快樂的編碼! – Tim

1

當然,它並不是一條線。每次單擊按鈕時,您都只需讀取第一行。

最好的辦法是將文件中的所有行讀取到List<string>,並有一個int counter,您可以根據它們是向前還是向後移動來遞增或遞減。每次只增加/減少,並將文本設置爲yourListVar[counter]

或者,如果您希望它每次從ReadLine()開始循環讀取文件,直到找到匹配計數器的索引爲止。

+0

好的很酷謝謝,但如果你注意到我的streamreader正在從那裏編碼的「靜態」文件名讀取。我希望它從動態文件名中讀取,就像用戶在第一個代碼塊中打開並選擇的那樣,我有 – Colin

+0

@Colin更新列表,並且每次打開一個新文件時將計數器設置爲0?理想情況下,爲了抽象,有一個函數可以填充該列表。 – RogueCSDev

+0

是的,可以工作,但就像我希望這個計數器通過在第一個代碼塊中打開的當前文件。如果你看到我在說什麼:設計是:用戶打開文件,文件的第一行文本顯示在窗體上,然後我有一個'上一個'和'下一個'按鈕,我想循環的文本行同樣的文件 – Colin