0

*EDIT: This doesn't happen on Windows but on Mono 4.2.2 Linux (C# Online Compiler).

I want to parse the protocol-relative URL and get the host name etc. For now I insert "http:" to the head before processing it since C# Uri class couldn't handle a protocol-relative URL. Could you tell me if there's any better way or any good library?

    // Protocol-relative URL
    var uriString = "//www.example.com/bluh/bluh.css";
    var uri = new Uri(uriString);
    Console.WriteLine(uriString); // "//www.example.com/bluh/bluh.css"
    Console.WriteLine(uri.Host); // "Empty" string

    // Absolute URL
    var fixUriString = uriString.StartsWith("//") ? "http:" + uriString : uriString;
    var fixUri = new Uri(fixUriString);
    Console.WriteLine(fixUriString); // "http://www.example.com/bluh/bluh.css"
    Console.WriteLine(fixUri.Host); // "www.example.com"
Tsukuru
  • 104
  • 1
  • 4
  • Possibly you could write your own `UriParser` - https://msdn.microsoft.com/en-us/library/system.uriparser.aspx – Blorgbeard Jul 01 '16 at 01:57

1 Answers1

3

This works:

    Uri uri = null;
    if(Uri.TryCreate("//forum.xda-developers.com/pixel-c", UriKind.Absolute, out uri))
    {
        Console.WriteLine(uri.Authority);
        Console.WriteLine(uri.Host);
    }

returns

forum.xda-developers.com
forum.xda-developers.com

It also worked for me using the Uri(string) constructor.

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
  • Thank you! You made me realized mono on Linux works differently. I switched to Windows then Uri(string) works perfectly. – Tsukuru Jul 01 '16 at 04:50