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

前端 未结 4 1569
死守一世寂寞
死守一世寂寞 2021-01-03 00:24

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.

相关标签:
4条回答
  • 2021-01-03 00:41

    Location can be different to CodeBase. E.g. for files in ASP.NET it likely to be resolved under c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET. See "Assembly.CodeBase vs. Assembly.Location" http://blogs.msdn.com/suzcook/archive/2003/06/26/57198.aspx

    0 讨论(0)
  • 2021-01-03 00:53

    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('/', '\\');
    }
    
    0 讨论(0)
  • 2021-01-03 00:57

    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);
    }
    
    0 讨论(0)
  • 2021-01-03 01:03

    Can you just use Assembly.Location?

    0 讨论(0)
提交回复
热议问题