Mohanapriya R Mohanapriya R
Updated date May 12, 2024
In this article, we will explore the process of converting Uniform Resource Identifiers (URIs) to strings in C#. Learn how the ToString() method of the Uri class simplifies this task.

Convert URI to Strings in C#

In C#, the Uri class is used to represent URIs. It provides methods to manipulate and retrieve various components of a URI. However, there are scenarios where you might need to convert a URI to a string, for instance, when you want to display it, store it, or pass it as a parameter in a method. The ToString() method of the Uri class is the simplest way to achieve this.

using System;

class Program
{
    static void Main()
    {
        // Sample URI
        Uri sampleUri = new Uri("https://www.example.com/path/page.html?query=123");

        // Convert URI to string
        string uriString = sampleUri.ToString();

        // Display the original URI and the converted string
        Console.WriteLine("Original URI: " + sampleUri);
        Console.WriteLine("Converted String: " + uriString);
    }
}

Output:

Original URI: https://www.example.com/path/page.html?query=123
Converted String: https://www.example.com/path/page.html?query=123

In this example, we create a Uri object representing a sample URI. The ToString() method is then used to convert this URI to a string. The program outputs both the original URI and the converted string.

Comments (0)

There are no comments. Be the first to comment!!!