Home > Blockchain >  C# How can I parse a url to get just the domain name?
C# How can I parse a url to get just the domain name?

Time:02-06

I want to get the domain name and only the domain name without the TLD Before: example.com After: example

I tried using the package domainname-parser but this did not work because my operation is being threaded and I get the error: The process cannot access the file 'PATH' because it is being used by another process.' Here:

var domaininfo = new DomainParser(new WebTldRuleProvider()).Parse(uri.Host);

CodePudding user response:

Hey man you could try this code:

    public static void Main(string[] args)
    {
        string urlString = "http://example.site.com/index.html";
        Console.WriteLine(GetDomainNameOfUrlString(urlString));
    }

    private static string GetDomainNameOfUrlString(string urlString)
    {
        var host = new Uri(urlString).Host;
        return host.Substring(host.LastIndexOf('.', host.LastIndexOf('.') - 1)   1);
    }

CodePudding user response:

it's easiest way to use Uri class, but it's not memory efficient.

you should use Span and implement it by yourself if you want memory efficient version.

 using System;
 
 public class HelloWorld
 {
     public static void Main(string[] args)
     {
         // you can use Uri class,
         var url = "https://www.youtube.com/watch?v=kgTeT3AIM4g";
         var uri = new Uri(url);
         Console.WriteLine(uri.Host); // www.youtube.com
     }
 }
  • Related