Extracting Path from OpenFileDialog path/filename

C#.NetParsingPath

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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);

Solution 2 - C#

how about this:

string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");

Solution 3 - C#

if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
    strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
}

Solution 4 - C#

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
}

Solution 5 - C#

Here's the simple way to do It !

string fullPath =openFileDialog1.FileName;
string directory;
directory = fullPath.Substring(0, fullPath.LastIndexOf('\\'));

Solution 6 - C#

This was all I needed for the full path to a file

@openFileDialog1.FileName

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin HainesView Question on Stackoverflow
Solution 1 - C#Jeff YatesView Answer on Stackoverflow
Solution 2 - C#Jan MacháčekView Answer on Stackoverflow
Solution 3 - C#MaxView Answer on Stackoverflow
Solution 4 - C#ShaahinView Answer on Stackoverflow
Solution 5 - C#AbdelView Answer on Stackoverflow
Solution 6 - C#WiiLFView Answer on Stackoverflow