2017-01-02 51 views
0

你好我想從我的Windows窗體應用程序的目錄中選擇一個文件,但我似乎無法找到任何將從文本框中刪除路徑的文件並且只保留文件名(例如:「C:\ Users \ Users \ Documents \ File.txt」將只是「File.txt」),它在選擇文件時保存輸出。選擇文件時從文本框中刪除文件的路徑C#Visual Studio

  OpenFileDialog openFileDialog1 = new OpenFileDialog(); 

     openFileDialog1.InitialDirectory = @"C:\OUTPUT"; 
     openFileDialog1.Title = "Browse exe Files"; 

     openFileDialog1.CheckFileExists = true; 
     openFileDialog1.CheckPathExists = true; 
     openFileDialog1.Filter = "exe files | *.exe"; 

     openFileDialog1.DefaultExt = "exe"; 
     openFileDialog1.FilterIndex = 2; 
     openFileDialog1.RestoreDirectory = true; 

     openFileDialog1.ReadOnlyChecked = true; 
     openFileDialog1.ShowReadOnly = true; 

     if (openFileDialog1.ShowDialog() == DialogResult.OK) 
     { 
      textBox6.Text = openFileDialog1.FileName; 
     } 

任何人都可以啓發我如何做到這一點?

感謝

+0

見http://stackoverflow.com/questions/6817639/get-filenames-without-path-of-a-specific-directory –

+0

只是爲了澄清,因爲我對你的具體有點不清楚問題是:路徑名稱顯示在對話框的文本框中,並且您希望文本框僅爲空白? – MathSquared

+0

@MathSquared什麼OP想要刪除文件的路徑,只留下它的名字。例如「C:\ Users \ MyUser \ Documents \ Text.txt」將只是「Text.txt」 –

回答

4

可以使用Path.GetFileName功能這一點。

textBox6.Text = System.IO.Path.GetFileName(openFileDialog1.FileName); 
+0

我這樣做了:string Path = @「C:\ OUTPUT」; 它給了我這個錯誤:'string'不包含'GetFileName'的定義,並且沒有找到接受'string'類型的第一個參數的擴展方法'GetFileName'(你是否缺少using指令或程序集引用?) –

+0

路徑不是字符串變量,而是類的名稱。我編輯了答案,使其更清晰。 –

+0

阿爾好吧,我明白了!它做到了!謝謝。新年快樂 –