How do I convert an absolute or relative URI path (e.g. /foo/bar.txt
) to a (segmentwise) corresponding relative file system path (e.g. foo\bar.txt
) in .NET?
My program is not an ASP.NET application.
NET (for example, the method new Uri(path) ) generally uses the 2-slash form; Java (for example, the method new URI(path) ) generally uses the 4-slash form.
A URI is a compact representation of a resource available to your application on the intranet or internet. The Uri class defines the properties and methods for handling URIs, including parsing, comparing, and combining. The Uri class properties are read-only; to create a modifiable object, use the UriBuilder class.
The AbsolutePath property contains the path information that the server uses to resolve requests for information. Typically this is the path to the desired information on the server's file system, although it also can indicate the application or script the server must run to provide the information.
Have you already tried Server.MapPath
?
or Uri.LocalPath
property? Something like following :
string uriString = "file://server/filename.ext"; // Lesson learnt - always check for a valid URI if(Uri.IsWellFormedUriString(uriString)) { Uri uri = new Uri(uriString); Console.WriteLine(uri.LocalPath); }
I figured out this way to produce a full absolute file system path from a relative or absolute URI and a base path.
With:
Uri basePathUri = new Uri(@"C:\abc\");
From a relative URI:
string filePath = new Uri(basePathUri, relativeUri).AbsolutePath;
From an absolute URI:
// baseUri is a URI used to derive a relative URI Uri relativeUri = baseUri.MakeRelativeUri(absoluteUri); string filePath = new Uri(basePathUri, relativeUri).AbsolutePath;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With