我在ASP.NET领域寻找类似Server.MapPath的东西,将Assembly.GetExecutingAssembly()。CodeBase的输出转换为带有驱动器号的文件路径。
以下代码适用于我尝试过的测试用例:
private static string ConvertUriToPath(string fileName) { fileName = fileName.Replace("file:///", ""); fileName = fileName.Replace("/", "\\"); return fileName; }
似乎.NET Framework中应该有更好的东西 - 我只是无法找到它。
答案 0 :(得分:18)
尝试查看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);
}
答案 1 :(得分:3)
我寻找了很多答案,最受欢迎的答案是使用Uri.LocalPath。但是,如果Path包含“#”,则System.Uri无法提供正确的LocalPath。详细信息为here。
我的解决方案是:
private static string ConvertUriToPath(string fileName)
{
Uri uri = new Uri(fileName);
return uri.LocalPath + Uri.UnescapeDataString(uri.Fragment).Replace('/', '\\');
}
答案 2 :(得分:0)
你能使用Assembly.Location
吗?
答案 3 :(得分:0)
位置可能与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