2015-04-23 18 views
1

我有這樣的代碼讀取文件內容到一個數組

private void button1_Click(object sender, EventArgs e) 
{ 
    Stream myStream; 

    OpenFileDialog openFileDialog1 = new OpenFileDialog(); 

    openFileDialog1.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*"; 
    openFileDialog1.FilterIndex = 1; 
    openFileDialog1.Multiselect = true; 

    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
    { 
     if ((myStream = openFileDialog1.OpenFile()) != null) 
     { 
      string strfilename = openFileDialog1.FileName; 
      string filetext = File.ReadAllText(strfilename); 

      richTextBox3.Text = filetext; // reads all text into one text box 
     } 
    } 
} 

我掙扎如何獲取文本文件的每一行,以不同的文本框或可能存儲在一個陣列,可以有一個人請幫助!

+4

如何使用'File.ReadAllLines'而不是'File.ReadAllText'? –

+0

你不應該使用dialog.OpenFile,然後File.ReadAllText,對話框有一個選項來驗證文件是否存在,然後就像@JonSkeet所說的那樣使用ReadAllLines。 –

回答

2

File.ReadAllText將讀取文件中的所有文本。

string filetext = File.ReadAllText("The file path"); 

如果你想單獨存儲每一行​​的陣列,File.ReadAllLines可以做到這一點。

string[] lines = File.ReadAllLines("The file path"); 
+0

謝謝!太棒了 – Sup

1

(可選)您可以使用以下命令返回字符串列表。然後,您可以將字符串列表直接綁定到控件,也可以迭代列表中的每個項目並以這種方式添加它們。如下所示:

public static List<string> GetLines(string filename) 
{ 
    List<string> result = new List<string>(); // A list of strings 

    // Create a stream reader object to read a text file. 
    using (StreamReader reader = new StreamReader(filename)) 
    { 
     string line = string.Empty; // Contains a single line returned by the stream reader object. 

     // While there are lines in the file, read a line into the line variable. 
     while ((line = reader.ReadLine()) != null) 
     { 
      // If the line is not empty, add it to the list. 
      if (line != string.Empty) 
      { 
       result.Add(line); 
      } 
     } 
    } 

    return result; 
} 
+1

似乎很多工作與File.ReadAllLines相比,加上您可以合理地確信框架庫已經過全面測試。我會避免重新發明輪子。 –

+0

好點!那麼這是另一種選擇,但Jon和你自己提到的那個顯然是兩者中最好的一個。 –