Domanda

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

È stato utile?

Soluzione 2

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?

Altri suggerimenti

I think you probably want to open the file using the default application. In which case, try this:

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

openFileDialog1.FileName contains the string of the full path.

If, instead of opening it, you would rather load the contents of that selected file into another string, try:

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    var fileContents = System.IO.File.ReadAllText(openFileDialog1.FileName);
    ...
    // your code to work with the string here...
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top