1

I'm still relatively new to C# programming and I'm having trouble parsing a URL string. I would like to take a URL like http://server.example.org and split it into separate strings like protocol, server, and domain name. Here is what my code looks like so far:

string url = "http://server.example.org";
string protocol = url.Substring(0, url.IndexOf(":")); // parse from beginning to colon to get protocol
string server = url.Substring(url.IndexOf("//") + 2, url.IndexOf(".")); // parse from // + 2 to first . for server
string domain = url.Substring(url.IndexOf(".") + 1); // the rest of the string should be the domain

The protocol string correctly shows http and domain correctly shows example.org, but the server string comes out as server.exampl instead of server as expected. What am I doing wrong?

1
  • 1
    Convert it to a Uri and then you can access all the parts you want via Uri.Scheme, .Host, .Segments, and .Fragment properties. Commented Oct 1, 2020 at 22:39

1 Answer 1

1

The Uri constructor is capable of parsing a URI. It has a wealth of properties that give you various attributes. However, if you want to split the Host you will need to do it manually

var uri = new Uri("http://server.example.org");
var split = uri.Host.Split('.');

Console.WriteLine(uri.Scheme);
Console.WriteLine(uri.Host);
Console.WriteLine(split[0]);
Console.WriteLine(string.Join(".",split.Skip(1)));

Output

http
server.example.org
server
example.org
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.