How retrieve only filename from save file dialog [duplicate]
Asked Answered
P

2

7

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.

Polyphagia answered 14/8, 2013 at 21:17 Comment(2)
Consider using search engines first... c# retrieve only filename from file path gives pretty decent shot at answer.Avarice
@cody-gray: this should not be marked as a duplicate. The linked question is for OpenFileDialog and this is SaveFileDialog. The accepted answer for the linked duplicate will not work for SaveFileDialog.Wheelwright
H
19

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

Helgoland answered 14/8, 2013 at 21:18 Comment(0)
P
2

Also found another solution to my problem

    FileInfo fi = new FileInfo(saveFileDialog1.FileName);
    string text = fi.Name;
Polyphagia answered 14/8, 2013 at 21:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.