C # Openfiledialog

When I open a file using this code

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

A window will appear and ask me to select a file (the file name is empty, as you can see in the image)

enter image description here

If I press the "Open" button a second time to open the file, the file name will display the path to the previous selected file (see image). How can I clear this path every time he clicks the open button?

enter image description here

+7
source share
6 answers

You are probably using the same instance of OpenFileDialog each time you click the button, which means that the previous file name is still stored in the FileName property. Before displaying the dialog again, you must clear the FileName property:

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

try the following:

 ofd.FileName = String.Empty; 
+6
source

You need to reset the file name.

  openFileDialog1.FileName= ""; 

or

  openFileDialog1.FileName= String.Empty() 
+3
source

you can simply add this line before calling ShowDialog() :

 ofd.FileName = String.Empty; 
+3
source

To clear only the file name (and not the selected path), you can set the FileName property to string.Empty .

+1
source
 private void button1_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); } private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { label1.Text = sender.ToString(); } 

How about this one.

0
source

All Articles