How can I get a full path of a given path (can be a directory or file, or even full path) using C#?

3k Views Asked by At

The closest I get is using new FileInfo(path).FullPath, but as far as I know FileInfo is for files only, not directory.

See also my comments to Jon Skeet's answer here for context.

8

There are 8 best solutions below

0
On BEST ANSWER

The Path class also gives you a lot of nice methods and properties, e.g. GetFullPath(). See MSDN for all details.

2
On

Use the DirectoryInfo class for paths to directories. Works much in the same matter as FileInfo.

Note that the property for the path is called FullName.

DirectoryInfo di = new DirectoryInfo(@"C:\Foo\Bar\");
string path = di.FullName;

If you want to determine whether a path is a file or a directory, you can use static methods from the Path class:

string path1 = @"C:\Foo\Bar.docx";
string path2 = @"C:\Foo\";

bool output1 = Path.HasExtension(path1); //Returns true
bool output2 = Path.HasExtension(path2); //Returns false

However, paths could also contain something that might resemble an extension, so you might want to use it in conjunction with some other checks, e.g. bool isFile = File.Exists(path);

0
On

You can use file.getdirectory to get this done.

1
On

I think it's-

DirectoryInfo.FullName
2
On

Try this:

String strYourFullPath = "";
IO.Path.GetDirectoryName(strYourFullPath)
0
On

Use the DirectoryInfo class which extends FileSystemInfo and will give the correct result for either files or directories.

        string path = @"c:\somefileOrDirectory";
        var directoryInfo = new DirectoryInfo(path);
        var fullPath = directoryInfo.FullName;
0
On
3
On

According to msdn, FileSystemInfo.FullName gets the full path of the directory or file, and can be applied to a FileInfo.

FileInfo fi1 = new FileInfo(@"C:\someFile.txt");
Debug.WriteLine(fi1.FullName); // Will produce C:\someFile.txt
FileInfo fi2 = new FileInfo(@"C:\SomeDirectory\");
Debug.WriteLine(fi2.FullName); // Will produce C:\SomeDirectory\