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


Answers

System.IO.Path.GetDirectoryName(filename)
Question

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".




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\"




You can use System.IO.Path.GetDirectory(filename), or turn the path into a FileInfo, and use FileInfo.Directory.

If you're doing other things with the path, the FileInfo 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 get the current Application Path using:

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

Good Luck!