Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 947
Even Mien Avatar asked Mar 23 '09 17:03

Even Mien


People also ask

How do I get the full path of the current file's directory?

To get current file's full path, you can use the os. path. abspath function. If you want only the directory path, you can call os.

How do I find the full directory in Linux?

The best Linux command to get file path is using pwd command. To use this command, type “pwd” into your terminal and press enter. This command will print the current working directory. The output will be the file path.

What is the full path to the directory?

The full path name is the path from the root directory (i.e., / ). ./my_script is the relative path name, because the path is given relatively to the current directory, which is denoted by . . So if you are in your home directory the full path is s.th.

How do I get the shell directory path?

2.1. To obtain the full path of a file, we use the readlink command. readlink prints the absolute path of a symbolic link, but as a side-effect, it also prints the absolute path for a relative path. In the case of the first command, readlink resolves the relative path of foo/ to the absolute path of /home/example/foo/.


1 Answers

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.

like image 67
Jon Skeet Avatar answered Oct 13 '22 21:10

Jon Skeet