【问题标题】:How retrieve only filename from save file dialog [duplicate]如何从保存文件对话框中仅检索文件名[重复]
【发布时间】:2013-08-17 00:57:00
【问题描述】:

我有一个保存文件对话框,我只想获取输入的文件名。相当于

    openfiledialog.SafeFileName;

保存文件对话框没有SafeFileName 属性,FileName 返回文件名、路径和扩展名。请问如何只提取文件名。

【问题讨论】:

  • 首先考虑使用搜索引擎...c# retrieve only filename from file path 给出了相当不错的答案。
  • @cody-gray:这不应该被标记为重复。链接的问题是针对 OpenFileDialog 的,这是 SaveFileDialog。已接受的链接副本的答案不适用于 SaveFileDialog。

标签: c# winforms savefiledialog filedialog


【解决方案1】:

如果您想要 带有 扩展名的文件名,请使用 Path.GetFileName()。如果您希望它没有扩展名,也可以使用Path.GetFileNameWithoutExtension()

public void Test(string fileName)
{
    string path = Path.GetDirectoryName(fileName);
    string filename_with_ext = Path.GetFileName(fileName);
    string filename_without_ext = Path.GetFileNameWithoutExtension(fileName);
    string ext_only = Path.GetExtension(fileName);
}

请参阅 MSDN 了解更多详细信息,尤其是 Path 类,它有许多有用的方法:

http://msdn.microsoft.com/en-us/library/System.IO.Path_methods.aspx

http://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx

http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension.aspx

【讨论】:

    【解决方案2】:

    还找到了我的问题的另一种解决方案

        FileInfo fi = new FileInfo(saveFileDialog1.FileName);
        string text = fi.Name;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多