【问题标题】:How to get just a File Name from the full path?如何从完整路径中获取文件名?
【发布时间】:2014-12-07 15:08:35
【问题描述】:

我不敢相信我不得不问这个,因为有简单的问题,然后有荒谬的问题.. 无论如何,由于显而易见的答案(不是我要寻找的答案),我实际上无法找到答案。

我有这样的代码:

 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,而不是完整路径。

提前致谢! !

【问题讨论】:

  • System.Io.Path.GetFileName(string);
  • 最肮脏的解决方法是textBox1.Text = odf.FileName.Substring(ofd.FileName.LastIndexOf("\\") + 1);

标签: c# file file-io classpath filenames


【解决方案1】:

您可以在Path Class 中使用Path.GetFileName Method

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 ''

【讨论】:

    【解决方案2】:

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

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

    path.getfilename

    openfiledialog.safefilename

    【讨论】:

    • 非常简单的解决方案,正如预期的那样。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 2010-09-30
    • 2010-11-27
    相关资源
    最近更新 更多