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?

Charlie Dobson
  • 193
  • 1
  • 11
  • 1
    [Convert it to a `Uri`](https://stackoverflow.com/a/1465728/8967612) and then you can access all the parts you want via [`Uri.Scheme`](https://learn.microsoft.com/en-us/dotnet/api/system.uri.scheme), `.Host`, `.Segments`, and `.Fragment` properties. – 41686d6564 stands w. Palestine Oct 01 '20 at 22:39

1 Answers1

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
TheGeneral
  • 79,002
  • 9
  • 103
  • 141