Extract path from OpenFileDialog path / filename

I am writing a small utility that starts with selecting a file, and then I need to select a folder. I would like to indicate by default the folder in which the selected file was selected.

OpenFileDialog.FileName returns the full path and file name - I want to get only part of the path (sans filename), so I can use this 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 for this, or do I need to use regex, split, trim, etc.

+62
c # parsing path
Jan 13 '09 at 13:51
source share
5 answers

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

The use is simple.

 string directoryPath = Path.GetDirectoryName(filePath); 
+84
Jan 13 '09 at 13:57
source share

how about this:

 string fullPath = ofd.FileName; string fileName = ofd.SafeFileName; string path = fullPath.Replace(fileName, ""); 
+18
Feb 15 '13 at 12:23
source share
 if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName; } 
+11
Jul 10 '12 at 17:13
source share

You can use FolderBrowserDialog instead of FileDialog and get the path from the OK result.

 FolderBrowserDialog browser = new FolderBrowserDialog(); string tempPath =""; if (browser.ShowDialog() == DialogResult.OK) { tempPath = browser.SelectedPath; // prints path } 
+3
Sep 21 '12 at 17:11
source share

Here is an easy way to do it!

 string fullPath =openFileDialog1.FileName; string directory; directory = fullPath.Substring(0, fullPath.LastIndexOf('\\')); 
0
Apr 26 '16 at 14:15
source share



All Articles