System.Uri fails to give correct AbsolutePath and LocalPath if the Path contains “#”

前端 未结 3 608
太阳男子
太阳男子 2021-01-06 06:02

I have C# code that is trying to get the LocalPath for a executing assembly using the following line of code:

Uri uri = new Uri(Assembly.GetExecut

相关标签:
3条回答
  • 2021-01-06 06:44

    I assume The URI functions are stripping away everything after the sharp # because it thinks its an anchor.

    URI are designed for identifying resources on the internet, so your # character would be an illegal character in the middle of any URI.

    Take even this question for example, the Title is

    System.Uri fails to give correct AbsolutePath and LocalPath if the Path contains “#”

    but the end of the URL has the "#" stripped away

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

    Why do you need to convert it into a URI anyway. The only difference between these 3 console.writelines is the fact that the first two are prefixed with File:///

    Console.WriteLine(Assembly.GetExecutingAssembly().CodeBase);  // 1
    Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
    Console.WriteLine(uri);                                       // 2
    Console.WriteLine(uri.LocalPath);                             // 3
    
    0 讨论(0)
  • 2021-01-06 06:45
    System.IO.FileInfo logger = new System.IO.FileInfo(Path.Combine(Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath), "settings.config"));
    

    Using EscapedCodeBase instead of CodeBase solves the problem. I dint realize that this was already handled until I stumbled on it.:)

    0 讨论(0)
  • 2021-01-06 06:49

    The Uri class is behaving as expected. # is not a valid part of a url. Imo this is an issue with CodeBase property. It returns a string unescaping special characters rendering it pretty much unreliable. Your options are:

    1) Always use EscapedCodeBase property instead.

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

    2) Or if you really have to deal with CodeBase property (if that is the only option), get the escaped part yourself.

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

    3) For file location of the loaded assembly, the easiest is to use Location property.

    var uri = Assembly.GetExecutingAssembly().Location;
    

    The issue has been reported several times, but MS insists that is how CodeBase is designed here, here, here and here.

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