6

我正在尝试使用以下代码将 .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);
            }
        }
    }
4

1 回答 1

27

如果您只需要完整的文本,您应该使用该函数File.ReadAllText- 将对话框中选择的文件名/路径传递给它 ( openFileDialog1.FileName)。

例如,要将内容加载到文本框中,您可以编写:

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

打开和使用流有点复杂,因为你应该查找 using - 语句

于 2012-12-16T10:39:09.720 回答