Search code examples
c#openfiledialog

Opening a specific file with openfiledialog


So I'm trying to make a text file open when I navigate to the file using openfiledialog. Here is my code:

        string path;
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            System.IO.StreamReader sr = new
               System.IO.StreamReader(openFileDialog1.FileName);
            path = sr.ReadToEnd();
            sr.Close();
        }

It will not open, here is the error I get: i.imgur.com/0eVWFAJ.png


Solution

  • If you just want to open the file on a new window, you should use Diagnostics.Process

    Like what @Baldric showed, and if you want to save the filename.

    string path = "";
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        path = openFileDialog1.FileName;
        System.Diagnostics.Process.Start(path);
    }
    

    and one more thing I noticed in your code. you want to return the filename but you use

    path = sr.ReadToEnd();
    

    is the text in the file contain a path of the file?