How to get only the directory name from SaveFileDialog.FileName

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

+6
string c # parsing
source share
4 answers

Using:

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

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

+12
source share

You can create a FileInfo object. It has the property Name, FullName and DirectoryName.

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

The Path object in System.IO parses it perfectly.

+1
source share

Since an illegal slash is not allowed in the file name, one simple way is to split the SaveFileDialog.Filename with String.LastIndexOf; eg:

 string filename = dialog.Filename; string path = filename.Substring(0, filename.LastIndexOf("\")); string file = filename.Substring(filename.LastIndexOf("\") + 1); 
0
source share

All Articles