Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting Path from OpenFileDialog path/filename

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??

like image 796
Kevin Haines Avatar asked Jan 13 '09 13:01

Kevin Haines


People also ask

How do I get the selected file from OpenFileDialog box?

OpenFileDialog component opens the Windows dialog box for browsing and selecting files. To open and read the selected files, you can use the OpenFileDialog. OpenFile method, or create an instance of the System. IO.


2 Answers

Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.

Usage is simple.

string directoryPath = Path.GetDirectoryName(filePath); 
like image 191
Jeff Yates Avatar answered Oct 12 '22 23:10

Jeff Yates


how about this:

string fullPath = ofd.FileName; string fileName = ofd.SafeFileName; string path = fullPath.Replace(fileName, ""); 
like image 20
Jan Macháček Avatar answered Oct 13 '22 01:10

Jan Macháček