Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a URI path to a relative file system path in .NET

Tags:

c#

.net

path

uri

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.

like image 973
acdx Avatar asked Mar 14 '10 12:03

acdx


People also ask

Can a URI be a path?

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.

What is URI in C#?

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.

What is absolute path in URI?

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.


2 Answers

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); } 
like image 55
Ashish Gupta Avatar answered Sep 27 '22 21:09

Ashish Gupta


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; 
like image 40
acdx Avatar answered Sep 27 '22 22:09

acdx