Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a .NET Framework method for converting file URIs to paths with drive letters?

I was looking for something like Server.MapPath in the ASP.NET realm to convert the output of Assembly.GetExecutingAssembly().CodeBase into a file path with drive letter.

The following code works for the test cases I've tried:

private static string ConvertUriToPath(string fileName)
{
    fileName = fileName.Replace("file:///", "");
    fileName = fileName.Replace("/", "\\");
    return fileName;
}

It seems like there should be something in the .NET Framework that would be much better--I just haven't been able to find it.

like image 530
Scott Lawrence Avatar asked Nov 10 '08 18:11

Scott Lawrence


2 Answers

Try looking at the Uri.LocalPath property.

private static string ConvertUriToPath(string fileName)
{
   Uri uri = new Uri(fileName);
   return uri.LocalPath;

   // Some people have indicated that uri.LocalPath doesn't 
   // always return the corret path. If that's the case, use
   // the following line:
   // return uri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped);
}
like image 64
Scott Dorman Avatar answered Nov 15 '22 06:11

Scott Dorman


I looked for an answer a lot, and the most popular answer is using Uri.LocalPath. But System.Uri fails to give correct LocalPath if the Path contains “#”. Details are here.

My solution is:

private static string ConvertUriToPath(string fileName)
{
   Uri uri = new Uri(fileName);
   return uri.LocalPath + Uri.UnescapeDataString(uri.Fragment).Replace('/', '\\');
}
like image 45
Artsiom Avatar answered Nov 15 '22 08:11

Artsiom