Search code examples
c#openfiledialog

c# Openfiledialog


When I open a file using this code

if (ofd.ShowDialog() == DialogResult.OK)
     text = File.ReadAllText(ofd.FileName, Encoding.Default);

A window appear and ask me to choose file (The File Name is blank as you can see on the image)

enter image description here

If I press second time the button Open to open a file the File Name show the path of the previous selected file (see on image) How I can clear this path every time he press Open button?

enter image description here


Solution

  • You are probably using the same instance of an OpenFileDialog each time you click the button, which means the previous file name is still stored in the FileName property. You should clear the FileName property before you display the dialog again:

    ofd.FileName = String.Empty;
    if (ofd.ShowDialog() == DialogResult.OK)
         text = File.ReadAllText(ofd.FileName, Encoding.Default);