2012-06-19 115 views
7

當我使用此代碼C#打開文件對話框

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

出現一個窗口,並要求我選擇文件打開一個文件(文件名是空白的,你可以看到在圖像上)

enter image description here

如果我第二次按下打開按鈕打開一個文件,文件名將顯示上一個選定文件的路徑(請參閱圖像)每次他按下打開按鈕時我該如何清除此路徑?

enter image description here

回答

11

您可能正在使用的OpenFileDialog的同一個實例每次單擊該按鈕,這意味着以前的文件名仍保存在FileName財產。你應該清除FileName屬性再次顯示該對話框之前:

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

你需要重新設置文件名。

openFileDialog1.FileName= ""; 

或者

openFileDialog1.FileName= String.Empty() 
1

要清除只是文件名(而不是選擇的路徑),你可以FileName屬性設置爲string.Empty

3

,你可以簡單地調用ShowDialog()前加入這一行:

ofd.FileName = String.Empty; 
0
private void button1_Click(object sender, EventArgs e) 
    { 
     openFileDialog1.ShowDialog(); 
    } 

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

這件怎麼樣。

6

試試這個:

ofd.FileName = String.Empty;