2014-12-07 160 views
0

我不敢相信我不得不問這個,因爲有簡單的問題&然後有荒謬的問題。 無論如何,我實際上無法找出答案,由於明顯的答案(而不是我'尋找)。如何從完整路徑獲取文件名?

我有這樣的代碼:

OpenFileDialog ofd = new OpenFileDialog(); 
      if(ofd.ShowDialog() == DialogResult.OK) 
      { 
       textBox1.Text = ofd.FileName; 
      } 

這工作好,因爲那時我有一個方法,那當然,我打開文件(不同形式)。 但是,要將此傳遞給我的其他窗體的查看方法,路徑(ofd.FileName)必須保持完整。

我的問題或問題是:如何從路徑中獲取文件的實際名稱? 我試過這個:textBox1.Text = ofd.FileName.LastIndexOf("\"); 上面的嘗試在編譯器中標記爲錯誤,因爲反斜槓被歸類爲換行符。

那麼,如何從路徑中獲取文件名?例如,可以說文件的名稱是:List1.text,我希望我的第二個表單textBox1.Text爲:List1.text,而不是完整路徑。

提前致謝! !

+2

'System.Io.Path.GetFileName(字符串);' – Plutonix 2014-12-07 15:10:39

+0

最髒的解決方法是'textBox1.Text = odf.FileName.Substring(ofd.FileName.LastIndexOf( 「\\」)+ 1);' – Oybek 2014-12-07 15:18:23

回答

1

您可以使用Path.GetFileName MethodPath Class

string fileName = @"C:\mydir\myfile.ext"; 
string path = @"C:\mydir\"; 
string result; 

result = Path.GetFileName(fileName); 
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    fileName, result); 

result = Path.GetFileName(path); 
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    path, result); 

// This code produces output similar to the following: 
// 
// GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext' 
// GetFileName('C:\mydir\') returns '' 

,如果你想擴展您可以使用Path.GetExtension Method

string fileName = @"C:\mydir.old\myfile.ext"; 
string path = @"C:\mydir.old\"; 
string extension; 

extension = Path.GetExtension(fileName); 
Console.WriteLine("GetExtension('{0}') returns '{1}'", 
    fileName, extension); 

extension = Path.GetExtension(path); 
Console.WriteLine("GetExtension('{0}') returns '{1}'", 
    path, extension); 

// This code produces output similar to the following: 
// 
// GetExtension('C:\mydir.old\myfile.ext') returns '.ext' 
// GetExtension('C:\mydir.old\') returns '' 
+1

偉大的解決方案,謝謝! – 2014-12-07 15:14:08

+0

@WowSkiBowse你歡迎.. – 2014-12-07 15:15:15

0

您可以從.NET 4.0及更高版本或獲取OpenFileDialog.SafeFileName用途:

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName); 

path.getfilename

openfiledialog.safefilename

+0

非常簡單的解決方案,如預期。謝謝 ! – 2014-12-07 15:13:39

相關問題