Why doesn't System.Uri recognize query parameter for local file path?

前端 未结 2 1553
感情败类
感情败类 2021-01-11 21:52

I need to add some additional query information to file path as query parameter to parse path later during files processing. I though that System.Uri class can hel

2条回答
  •  执笔经年
    2021-01-11 22:05

    This is a bug which Microsoft won't fix : Bug 594562 As you can see they propose reflection as an workaround:

    ...
    Console.WriteLine("Before");
    Uri fileUri = new Uri("file://host/path/file?query#fragment");
    Console.WriteLine("AbsoluteUri: " + fileUri.AbsoluteUri);
    Console.WriteLine("ToString: " + fileUri.ToString());
    Console.WriteLine("LocalPath: " + fileUri.LocalPath);
    Console.WriteLine("Query: " + fileUri.Query);
    Console.WriteLine("Fragment: " + fileUri.Fragment);
    
    Type uriParserType = typeof(UriParser);
    FieldInfo fileParserInfo = uriParserType.GetField("FileUri", BindingFlags.Static | BindingFlags.NonPublic);
    UriParser fileParser = (UriParser)fileParserInfo.GetValue(null);
    FieldInfo fileFlagsInfo = uriParserType.GetField("m_Flags", BindingFlags.NonPublic | BindingFlags.Instance);
    int fileFlags = (int)fileFlagsInfo.GetValue(fileParser);
    int mayHaveQuery = 0x20;
    fileFlags |= mayHaveQuery;
    fileFlagsInfo.SetValue(fileParser, fileFlags);
    
    Console.WriteLine();
    Console.WriteLine("After");
    fileUri = new Uri("file://host/path/file?query#fragment");
    Console.WriteLine("AbsoluteUri: " + fileUri.AbsoluteUri);
    Console.WriteLine("ToString: " + fileUri.ToString());
    Console.WriteLine("LocalPath: " + fileUri.LocalPath);
    Console.WriteLine("Query: " + fileUri.Query);
    Console.WriteLine("Fragment: " + fileUri.Fragment);  
    ...  
    

提交回复
热议问题