如何从保存文件对话框中仅检索文件名

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

openfiledialog.SafeFileName; 

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

如果您希望扩展名的文件名使用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

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

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