C# - Read .txt file into TextBox

有些话、适合烂在心里 提交于 2019-11-28 04:16:34

问题


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?

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);
            }
        }
    }

回答1:


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).

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



来源:https://stackoverflow.com/questions/13900441/c-sharp-read-txt-file-into-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!