C
C#15mo ago
Kiel

Parsing an arbitrary file path as a Uri or similar

Hello there. I would like to be able to parse the following inputs in such a way that I'm aware if they are a relative or absolute path:
path/to/file.txt -> "Relative"
/path/to/file.txt -> "Absolute"
./path/to/file.txt -> "Relative"
path/to/file.txt -> "Relative"
/path/to/file.txt -> "Absolute"
./path/to/file.txt -> "Relative"
I'm having trouble getting this to work with Uri.TryCreate(). they all return false for their IsAbsoluteUri properties, when at least the second one should be true. I'm not sure what properties or methods I should utilize to obtain the information I'm after. Any pointers/tips?
5 Replies
MODiX
MODiX15mo ago
Kouhai#8274
REPL Result: Success
Path.IsPathRooted("path/to/file.txt");
Path.IsPathRooted("/path/to/file.txt");
Path.IsPathRooted(".path/to/file.txt");
Path.IsPathRooted("path/to/file.txt");
Path.IsPathRooted("/path/to/file.txt");
Path.IsPathRooted(".path/to/file.txt");
Compile: 535.942ms | Execution: 28.784ms | React with ❌ to remove this embed.
Kouhai
Kouhai15mo ago
Idk how to make modix show the output but this should work It'll return true for absolute paths
Kiel
Kiel15mo ago
Neat, that does seem to work. I actually realized, this is pointless. File.ReadAllText already supports relative paths, so these three examples work right out of the box. I had a feeling I was overthinking things. whenlifegetsatyou
Kouhai
Kouhai15mo ago
Oh <a:Haato_Notlikethis:714703964741828629>
MODiX
MODiX15mo ago
JakenVeina#1758
REPL Result: Success
Console.WriteLine(Path.IsPathRooted("path/to/file.txt"));
Console.WriteLine(Path.IsPathRooted("/path/to/file.txt"));
Console.WriteLine(Path.IsPathRooted(".path/to/file.txt"));
Console.WriteLine(Path.IsPathRooted("path/to/file.txt"));
Console.WriteLine(Path.IsPathRooted("/path/to/file.txt"));
Console.WriteLine(Path.IsPathRooted(".path/to/file.txt"));
Console Output
False
True
False
False
True
False
Compile: 572.202ms | Execution: 26.753ms | React with ❌ to remove this embed.