是否有.NET Framework方法将文件URI转换为带有驱动器号的路径?

我在ASP.NET领域寻找类似Server.MapPath的东西,将Assembly.GetExecutingAssembly()。CodeBase的输出转换为带有驱动器号的文件路径。

以下代码适用于我尝试过的测试用例:

私有静态字符串ConvertUriToPath(string fileName)
 {
     fileName = fileName.Replace(“file:///”,“”);
     fileName = fileName.Replace(“/”,“\\”);
     return fileName;
 }

似乎.NET Framework中应该有更好的东西 – 我只是无法找到它。

尝试查看Uri.LocalPath属性。

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); } 

我找了很多答案,最流行的答案是使用Uri.LocalPath 。 但是,如果Path包含“#”,则System.Uri无法提供正确的LocalPath。 细节在这里 。

我的解决方案是:

 private static string ConvertUriToPath(string fileName) { Uri uri = new Uri(fileName); return uri.LocalPath + Uri.UnescapeDataString(uri.Fragment).Replace('/', '\\'); } 

你能使用Assembly.Location吗?

位置可能与CodeBase不同。 例如,对于ASP.NET中的文件,它可能在c:\ WINDOWS \ Microsoft.NET \ Framework \ v2.0.50727 \ Temporary ASP.NET下解析。 请参阅“Assembly.CodeBase与Assembly.Location” http://blogs.msdn.com/suzcook/archive/2003/06/26/57198.aspx