I'm writing a little utility that starts with selecting a file, and then I need to select a folder. I'd like to default the folder to where the selected file was.
OpenFileDialog.FileName
returns the full path & filename - what I want is to obtain just the path portion (sans filename), so I can use that as the initial selected folder.
private System.Windows.Forms.OpenFileDialog ofd;
private System.Windows.Forms.FolderBrowserDialog fbd;
...
if (ofd.ShowDialog() == DialogResult.OK)
{
string sourceFile = ofd.FileName;
string sourceFolder = ???;
}
...
fbd.SelectedPath = sourceFolder; // set initial fbd.ShowDialog() folder
if (fbd.ShowDialog() == DialogResult.OK)
{
...
}
Are there any .NET methods to do this, or do I need to use regex, split, trim,
etc??
Here's the simple way to do It !
how about this:
Use the
Path
class fromSystem.IO
. It contains useful calls for manipulating file paths, includingGetDirectoryName
which does what you want, returning the directory portion of the file path.Usage is simple.
You can use FolderBrowserDialog instead of FileDialog and get the path from the OK result.