Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one get an absolute or normalized file path in .NET?

Tags:

.net

filepath

How can one with minimal effort (using some already existing facility, if possible) convert paths like c:\aaa\bbb\..\ccc to c:\aaa\ccc?

like image 907
mark Avatar asked Aug 12 '09 14:08

mark


People also ask

How do you find the absolute path?

To find the full absolute path of the current directory, use the pwd command. Once you've determined the path to the current directory, the absolute path to the file is the path plus the name of the file.

What is a normalized file path?

Normalizing a path involves modifying the string that identifies a path or file so that it conforms to a valid path on the target operating system. Normalization typically involves: Canonicalizing component and directory separators. Applying the current directory to a relative path.

What is the absolute path name of the directory the file is located in?

Regardless of where you are working in the file system, you can always find a directory or file by specifying its absolute path name. Absolute path names start with a slash (/), the symbol representing the root directory. The path name /A/D/9 is the absolute path name for 9.

What are absolute and relative file paths?

An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words,we can say that an absolute path is a complete path from start of actual file system from / directory. Relative path. Relative path is defined as the path related to the present working directly(pwd) ...


1 Answers

I would write it like this:

public static string NormalizePath(string path) {     return Path.GetFullPath(new Uri(path).LocalPath)                .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)                .ToUpperInvariant(); } 

This should handle few scenarios like

  1. uri and potential escaped characters in it, like

    file:///C:/Test%20Project.exe -> C:\TEST PROJECT.EXE

  2. path segments specified by dots to denote current or parent directory

    c:\aaa\bbb\..\ccc -> C:\AAA\CCC

  3. tilde shortened (long) paths

    C:\Progra~1\ -> C:\PROGRAM FILES

  4. inconsistent directory delimiter character

    C:/Documents\abc.txt -> C:\DOCUMENTS\ABC.TXT

Other than those, it can ignore case, trailing \ directory delimiter character etc.

like image 136
nawfal Avatar answered Nov 15 '22 15:11

nawfal