C# - 将 .txt 文件读入 TextBox

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13900441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:04:11  来源:igfitidea点击:

C# - Read .txt file into TextBox

c#listtextboxtext-files

提问by Jeagr

I am trying to read a .txt file into a multi-line text box with the following code. I have gotten the file dialog button to work perfectly, but I am not sure how to get the actual text from the fiile into the textbox. Here is my code. Can you help?

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

采纳答案by user287107

if you just need the complete text, you should use the function File.ReadAllText- pass it the FileName/Path selected in the dialoge (openFileDialog1.FileName).

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

to load for example the content into a textbox, you can write:

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

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

opening and using streams is a little bit more complicated, for that you should look up the using - statement

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