How to get domain from url using C#? example: from https://test.ru/api/items?id=3 get:…
- User
How to get domain from url using C#? example: from https://test.ru/api/items?id=3 get: https://test.ru
- Assistant
To extract the domain from a URL in C#, you can use the
Uriclass, which provides methods to parse and manipulate URI values. Here's a simple example that demonstrates how to do this:csharpusing System; class Program { static void Main() { string url = "https://test.ru/api/items?id=3"; // Create a Uri instance from the URL Uri uri = new Uri(url); // Get the scheme and authority, which together form the domain string domain = $"{uri.Scheme}://{uri.Authority}"; Console.WriteLine(domain); // Output: https://test.ru } }Explanation:
-
Uri Class: The class is used to parse and work with URIs. You create a new instance of it by passing the URL string to its constructor.
-