Search code examples
c#.netwinformsopenfiledialog

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.


Solution

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