tags:

views:

579

answers:

4
+4  Q: 

C# Save Dialogs

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

A: 

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);
Rob
+1  A: 

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

Jay Mooney
+2  A: 

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);
Jake Pearson
+10  A: 

Use...

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

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

Adam Wright