How retrieve only filename from save file dialog [

2019-04-08 09:57发布

This question already has an answer here:

I have a save file dialog and i want to get only the filename entered. Equivalent for

    openfiledialog.SafeFileName;

Save file dialog has no SafeFileName Property and FileName returns both filename, path and extension. Pls how do i extract only file name.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-08 10:29

If you want the filename with extension use Path.GetFileName(). If you want it without the extension as well use 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);
}

See MSDN for further details, especially the Path class which has a number of useful methods:

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

查看更多
可以哭但决不认输i
3楼-- · 2019-04-08 10:49

Also found another solution to my problem

    FileInfo fi = new FileInfo(saveFileDialog1.FileName);
    string text = fi.Name;
查看更多
登录 后发表回答