【问题标题】:System.Uri fails to give correct AbsolutePath and LocalPath if the Path contains "#"如果路径包含“#”,System.Uri 无法提供正确的 AbsolutePath 和 LocalPath
【发布时间】:2009-05-22 06:27:01
【问题描述】:

我有 C# 代码尝试使用以下代码行为正在执行的程序集获取 LocalPath

Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;

这段代码适用于各种路径。它开始无法提供正确的AbsolutePathLocalpath,因为执行的程序集路径中包含一个#。

Assembly.GetExecutingAssembly().CodeBase"C:\c#\ExcelAddin1.1.0\GSRExcelPlugin\bin\Debug\Common.dll"

但是 new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath 给出“C:\c”,而它应该给出“C:\c#\ExcelAddin1.1.0\GSRExcelPlugin\bin\Debug\”。

我有什么需要处理的,或者 Uri 类的使用方式有什么问题吗?

如果这是一个 .net 框架问题,我应该如何将此问题报告给 Microsoft?

【问题讨论】:

    标签: c# .net


    【解决方案1】:
    System.IO.FileInfo logger = new System.IO.FileInfo(Path.Combine(Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath), "settings.config"));
    

    使用 EscapedCodeBase 代替 CodeBase 可以解决问题。我没有意识到这已经被处理了,直到我偶然发现它。:)

    【讨论】:

    • 该死:不适用于以下目录:Test\Space( )(#)(%20){[&],@,%}\Release ... %20 处理不正确
    • 这个解决方案对我有用,我在路径中有一个空格、一个 (x86) 字符和一个 #。谢谢!
    【解决方案2】:

    Uri 类的行为符合预期。 # 不是 URL 的有效部分。 Imo 这是CodeBase 属性的问题。它返回一个字符串,不转义特殊字符,使其非常不可靠。您的选择是:

    1) 始终使用 EscapedCodeBase 属性。

    var uri = new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath;
    

    2) 或者,如果您确实需要处理 CodeBase 属性(如果这是唯一的选择),请自己获取转义部分。

    var x = new Uri(Assembly.GetExecutingAssembly().CodeBase);
    var uri = x.LocalPath + Uri.UnescapeDataString(x.Fragment).Replace('/', '\\');
    

    3) 对于已加载程序集的文件位置,最简单的方法是使用Location 属性。

    var uri = Assembly.GetExecutingAssembly().Location;
    

    该问题已多次报告,但 MS 坚持认为 CodeBase 是这样设计的 herehereherehere

    【讨论】:

    • 至少Uri与自身一致。如果我执行new Uri(new Uri("C:\\"), "#%23"),则会得到file:///C:/%23%2523(这意味着它将内插路径视为文件路径而不是URI 样式的路径)。
    【解决方案3】:

    我假设 URI 函数正在剥离尖锐的 # 之后的所有内容,因为它认为它是一个锚点。

    URI 旨在识别 Internet 上的资源,因此您的 # 字符将是任何 URI 中间的非法字符。

    以这个问题为例,标题是

    如果路径包含“#”,System.Uri 无法提供正确的 AbsolutePath 和 LocalPath

    但 URL 末尾的“#”被去掉了

    system-uri-fails-to-give-correct-absolutepath-and-localpath-if-the-path-contains

    为什么还需要将其转换为 URI。这 3 个 console.writelines 之间的唯一区别是前两个以 File:/// 为前缀

    Console.WriteLine(Assembly.GetExecutingAssembly().CodeBase);  // 1
    Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
    Console.WriteLine(uri);                                       // 2
    Console.WriteLine(uri.LocalPath);                             // 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 2014-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 2015-10-01
      • 2012-03-10
      相关资源
      最近更新 更多