Question

What would be the easiest way to separate the directory name from the file name when dealing with SaveFileDialog.FileName in C#?

Was it helpful?

Solution

Use:

System.IO.Path.GetDirectoryName(saveDialog.FileName)

(and the corresponding System.IO.Path.GetFileName). The Path class is really rather useful.

OTHER TIPS

You could construct a FileInfo object. It has a Name, FullName, and DirectoryName property.

var file = new FileInfo(saveFileDialog.FileName);
Console.WriteLine("File is: " + file.Name);
Console.WriteLine("Directory is: " + file.DirectoryName);

The Path object in System.IO parses it pretty nicely.

Since the forward slash is not allowed in the filename, one simple way is to divide the SaveFileDialog.Filename using String.LastIndexOf; for example:

string filename = dialog.Filename;
string path = filename.Substring(0, filename.LastIndexOf("\"));
string file = filename.Substring(filename.LastIndexOf("\") + 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top