a1204773
a1204773

Reputation: 7043

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

Upvotes: 7

Views: 20869

Answers (6)

Clint Ceballos
Clint Ceballos

Reputation: 151

try this:

ofd.FileName = String.Empty;

Upvotes: 6

9T9
9T9

Reputation: 698

private void button1_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();
    }

    private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
    {
        label1.Text = sender.ToString();
    }

What about this one.

Upvotes: 0

John Woo
John Woo

Reputation: 263723

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

ofd.FileName = String.Empty;

Upvotes: 3

MatthiasG
MatthiasG

Reputation: 4532

To clear just the filename (and not the selected path), you can set the property FileName to string.Empty.

Upvotes: 1

Marlon
Marlon

Reputation: 20312

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

Upvotes: 11

Gaz Winter
Gaz Winter

Reputation: 2989

You need to reset the filename.

   openFileDialog1.FileName= "";

Or

   openFileDialog1.FileName= String.Empty()

Upvotes: 3

Related Questions