c# Openfiledialog

a1204773 picture a1204773 · Jun 19, 2012 · Viewed 19.3k times · Source

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

Answer

Marlon picture Marlon · Jun 19, 2012

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