System.Uri class truncates trailing '.' characters

馋奶兔 提交于 2019-12-01 15:14:00

问题


If I create a Uri class instance from string that has trailing full stops - '.', they are truncated from the resulting Uri object.

For example in C#:

Uri test = new Uri("http://server/folder.../");
test.PathAndQuery;

returns "/folder/" instead of "/folder.../".

Escaping "." with "%2E" did not help.

How do I make the Uri class to keep trailing period characters?


回答1:


You can use reflection before your calling code.

MethodInfo getSyntax = typeof(UriParser).GetMethod("GetSyntax", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
FieldInfo flagsField = typeof(UriParser).GetField("m_Flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (getSyntax != null && flagsField != null)
{
      foreach (string scheme in new[] { "http", "https" })
      {
          UriParser parser = (UriParser)getSyntax.Invoke(null, new object[] { scheme });
          if (parser != null)
          {
              int flagsValue = (int)flagsField.GetValue(parser);
              // Clear the CanonicalizeAsFilePath attribute
              if ((flagsValue & 0x1000000) != 0)
                 flagsField.SetValue(parser, flagsValue & ~0x1000000);
           }
       }
}

Uri test = new Uri("http://server/folder.../");
Console.WriteLine(test.PathAndQuery);

This has been submitted to Connect and the workaround above was posted there.



来源:https://stackoverflow.com/questions/6240203/system-uri-class-truncates-trailing-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!