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

6 c# filedialog savefiledialog winforms

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

    openfiledialog.SafeFileName;
Run Code Online (Sandbox Code Playgroud)

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

Llo*_*oyd 18

如果你想要的文件名扩展使用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);
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅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