Url Parsing in C#

Here’s the translation of the URL parsing example from Go to C#:

Our URL parsing program demonstrates how to parse and extract different components from a URL in C#.

using System;
using System.Collections.Specialized;
using System.Web;

class UrlParsing
{
    static void Main()
    {
        // We'll parse this example URL, which includes a
        // scheme, authentication info, host, port, path,
        // query params, and query fragment.
        string s = "postgres://user:pass@host.com:5432/path?k=v#f";

        // Parse the URL and ensure there are no errors.
        Uri u;
        if (!Uri.TryCreate(s, UriKind.Absolute, out u))
        {
            throw new Exception("Invalid URL");
        }

        // Accessing the scheme is straightforward.
        Console.WriteLine(u.Scheme);

        // UserInfo contains all authentication info
        Console.WriteLine(u.UserInfo);
        string[] userInfoParts = u.UserInfo.Split(':');
        Console.WriteLine(userInfoParts[0]);  // Username
        Console.WriteLine(userInfoParts[1]);  // Password

        // The Host contains both the hostname and the port,
        // if present.
        Console.WriteLine(u.Host);
        Console.WriteLine(u.DnsSafeHost);
        Console.WriteLine(u.Port);

        // Here we extract the path and the fragment after
        // the #.
        Console.WriteLine(u.AbsolutePath);
        Console.WriteLine(u.Fragment);

        // To get query params in a string of k=v format,
        // use Query. You can also parse query params
        // into a NameValueCollection.
        Console.WriteLine(u.Query);
        NameValueCollection queryParams = HttpUtility.ParseQueryString(u.Query);
        foreach (string key in queryParams.AllKeys)
        {
            Console.WriteLine($"{key}: {queryParams[key]}");
        }
    }
}

Running our URL parsing program shows all the different pieces that we extracted.

$ dotnet run
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
#f
?k=v
k: v

This C# program demonstrates URL parsing using the System.Uri class, which provides similar functionality to Go’s url.Parse. The HttpUtility.ParseQueryString method is used to parse query parameters, returning a NameValueCollection which is similar to the map returned by Go’s url.ParseQuery.

Note that C# doesn’t have a direct equivalent to Go’s net.SplitHostPort, but the Uri class provides separate properties for the host and port, making it unnecessary in this case.

Remember to add a reference to System.Web in your project file or use the appropriate NuGet package to access the HttpUtility class.