[c#] 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??

This question is related to c# .net parsing path

The answer is


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

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

Here's the simple way to do It !

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

how about this:

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

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
}

how about this:

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

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

Here's the simple way to do It !

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

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
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to parsing

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java?

Examples related to path

Get Path from another app (WhatsApp) How to serve up images in Angular2? How to create multiple output paths in Webpack config Setting the correct PATH for Eclipse How to change the Jupyter start-up folder Setting up enviromental variables in Windows 10 to use java and javac How do I edit $PATH (.bash_profile) on OSX? Can't find SDK folder inside Android studio path, and SDK manager not opening Get the directory from a file path in java (android) Graphviz's executables are not found (Python 3.4)