如何从完整路径获取文件名?

问题描述:

我不敢相信我不得不问这个,因为有简单的问题&然后有荒谬的问题。 无论如何,我实际上无法找出答案,由于明显的答案(而不是我'寻找)。如何从完整路径获取文件名?

我有这样的代码:

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

您可以使用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

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

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

path.getfilename

openfiledialog.safefilename

+0

非常简单的解决方案,如预期。谢谢 ! – 2014-12-07 15:13:39