简体   繁体   中英

How to use openfiledialog to open any file as text in C#?

I am writing a winforms program in C# that uses the openfiledialog. I would like it to be able to take the file that the user selected and open it as text, regardless of the file type.

I tried it like this:

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    textBox1.Text = Process.Start("notepad.exe", openFileDialog1.ToString()).ToString();
}

However, that didn't work and I'm not sure if I"m even on the right track.

You should use this code:
First add this namespace :

    using System.IO;

Then add this codes to your function:

    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
    if (openFileDialog.ShowDialog()== DialogResult.OK)
    {
            textBox1.Text = File.ReadAllText(openFileDialog.FileName);
    }

To open the file using notepad, you need to pass the file name as second parameter of Start method. For example:

using (var ofd = new OpenFileDialog())
{
    if(ofd.ShowDialog()== DialogResult.OK)
    {
        System.Diagnostics.Process.Start("notepad.exe", ofd.FileName);
    }
}

Also if for any reason while knowing that not all file contents are text, you are going to read the file content yourself:

using (var ofd = new OpenFileDialog())
{
    if(ofd.ShowDialog()== DialogResult.OK)
    {
        var txt = System.IO.File.ReadAllText(ofd.FileName);
    }
}

What you are doing at the moment is starting a Process with the argument openFileDialog1.ToString() , calling ToString() on the process and setting this as text in the TextBox. If the path was valid, the result would probably be something like "System.Diagnostics.Process". But since you use openFileDialog1.ToString() as a path, your application probably crashes with a file not found error.

To get the selected file of an OpenFileDialog , use openFileDialog1.FileName . (See the docs here )

What I think you actually want to do, is read from the file and write its contents as text to the TextBox. To do this, you need a StreamReader , like so:

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    using(var reader = new StreamReader(openFileDialog1.FileName))
    {
        textBox1.Text = reader.ReadToEnd();
    }
}

This way, you open the file with the StreamReader, read its contents and then assign them to the text box.

The using statement is there because a StreamReader needs to be disposed of after you're done with it so that the file is no longer in use and all resources are released. The using statement does this for you automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM