2012-12-16 50 views
3

我試圖用下面的代碼將.txt文件讀入多行文本框中。我已經獲得了文件對話框按鈕的完美工作,但我不確定如何從文件中獲取實際的文本。這是我的代碼。你能幫我嗎?C# - 將文本文件讀入.txt文件

private void button_LoadSource_Click(object sender, EventArgs e) 
    { 
     Stream myStream = null; 
     OpenFileDialog openFileDialog1 = new OpenFileDialog(); 

     openFileDialog1.InitialDirectory = "c:\\"; 
     openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; 
     openFileDialog1.FilterIndex = 2; 
     openFileDialog1.RestoreDirectory = true; 

     if (openFileDialog1.ShowDialog() == DialogResult.OK) 
     { 
      try 
      { 
       if ((myStream = openFileDialog1.OpenFile()) != null) 
       { 
        using (myStream) 
        { 
         // Insert code to read the stream here. 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); 
      } 
     } 
    } 

回答

20

如果你只需要完整的文本,你應該使用功能File.ReadAllText - 通過它在dialoge(openFileDialog1.FileName)選擇的文件名/路徑。

加載例如內容到一個文本框,你可以寫:

textbox1.Text = File.ReadAllText(openFileDialog1.FileName); 

打開和使用流是多一點點複雜,你應該查查使用 - 聲明

+0

那完美地工作。謝謝! – Jeagr