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



6 Answers

System.IO.Path.GetDirectoryName(filename)
how to get folder path in c# windows application

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




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



Just incase someone else needs it, what I used for my relative path was:

string rootPath = "MyRootDir/MyFolder1/MyFolder2/myFile.pdf";
while (!string.IsNullOrWhiteSpace(Path.GetDirectoryName(rootPath))) 
{
    rootPath = Path.GetDirectoryName(rootPath);
} 
Console.WriteLine(rootPath); //Will print: "MyRootDir"



Related