[c#] How do I get the directory from a file's full path?

What is the simplest way to get the directory that a file is in? I'm using this to set a working directory.

string filename = @"C:\MyDirectory\MyFile.bat";

In this example, I should get "C:\MyDirectory".

This question is related to c# .net file file-io directory

The answer is


If you've definitely got an absolute path, use Path.GetDirectoryName(path).

If you might only get a relative name, use new FileInfo(path).Directory.FullName.

Note that Path and FileInfo are both found in the namespace System.IO.


You can get the current Application Path using:

string AssemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString();

Good Luck!


Path.GetDirectoryName(Context.Parameters["assemblypath"])


 string path= @"C:\Users\username\Desktop\FolderName"
  string Dirctory = new FileInfo(path).Name.ToString();
//output FolderName

System.IO.Path.GetDirectoryName(filename)

First, you have to use System.IO namespace. Then;

string filename = @"C:\MyDirectory\MyFile.bat";
string newPath = Path.GetFullPath(fileName);

or

string newPath = Path.GetFullPath(openFileDialog1.FileName));

You can use Path.GetDirectoryName and just pass in the filename.

MSDN Link


If you are working with a FileInfo object, then there is an easy way to extract a string representation of the directory's full path via the DirectoryName property.

Description of the FileInfo.DirectoryName Property via MSDN:

Gets a string representing the directory's full path.

Sample usage:

string filename = @"C:\MyDirectory\MyFile.bat";
FileInfo fileInfo = new FileInfo(filename);
string directoryFullPath = fileInfo.DirectoryName; // contains "C:\MyDirectory"

Link to the MSDN documentation.


Path.GetDirectoryName(filename);

In my case, I needed to find the directory name of a full path (of a directory) so I simply did:

var dirName = path.Split('\\').Last();

You can use System.IO.Path.GetDirectoryName(fileName), or turn the path into a FileInfo using FileInfo.Directory.

If you're doing other things with the path, the FileInfo class may have advantages.


Use below mentioned code to get the folder path

Path.GetDirectoryName(filename);

This will return "C:\MyDirectory" in your case


You can use Path.GetFullPath for most of the case. But if you want to get the path also in the case of the file name is relatively located then you can use the below generic method:

string GetPath(string filePath)
{
  return Path.GetDirectoryName(Path.GetFullPath(filePath))
}

For example:

GetPath("C:\Temp\Filename.txt") return "C:\Temp\"

GetPath("Filename.txt") return current working directory like "C:\Temp\"


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 file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js

Examples related to directory

Moving all files from one directory to another using Python What is the reason for the error message "System cannot find the path specified"? Get folder name of the file in Python How to rename a directory/folder on GitHub website? Change directory in Node.js command prompt Get the directory from a file path in java (android) python: get directory two levels up How to add 'libs' folder in Android Studio? How to create a directory using Ansible Troubleshooting misplaced .git directory (nothing to commit)