2012-12-16 34 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