Mohanapriya R Mohanapriya R
Updated date May 18, 2024
In this article, we will learn how to convert strings to URIs in C#. Explore examples and ensure error-free URI handling for your web development projects.

Convert Strings to URI in C#

A URI is a string of characters that uniquely identifies a particular resource. URIs are widely used in web development for various purposes, including creating hyperlinks, handling API endpoints, and more. Let's start with a simple C# program that shows how to convert strings to URIs.

using System;

class Program
    static void Main()
        // Example string
        string urlString = "";

            // Converting string to URI
            Uri uri = new Uri(urlString);

            // Displaying the converted URI
            Console.WriteLine("Original String: " + urlString);
            Console.WriteLine("Converted URI: " + uri);
        catch (UriFormatException ex)
            // Handling invalid URI format
            Console.WriteLine("Error: " + ex.Message);


Original String:
Converted URI:
  • We declare a string urlString representing a sample URL.
  • Using the Uri class constructor, we convert the string to a URI.
  • The program then displays the original string and the converted URI.
  • We handle potential errors by catching a UriFormatException if the input string is not a valid URI.

Comments (0)

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