C# `Uri.IsWellFormedOriginalString()`: Validating URI Syntax
Learn how to validate URIs (Uniform Resource Identifiers) in C# using the `Uri.IsWellFormedOriginalString()` method. This tutorial explains how to check for compliance with RFC 3986 standards, preventing errors caused by malformed URIs in your network applications.
Using C#'s `Uri.IsWellFormedOriginalString()` Method for URI Validation
The C# `Uri.IsWellFormedOriginalString()` method checks if a URI string conforms to the standard URI syntax rules defined in RFC 3986. This is a crucial method for validating URIs, particularly when dealing with user-supplied data or dynamically generated URIs.
Understanding URI Syntax and Well-Formedness
A well-formed URI follows specific rules for its components (scheme, authority, path, query, fragment). A malformed URI is one that doesn't adhere to this syntax and may cause errors when used in network operations.
`Uri.IsWellFormedOriginalString()` Method
public bool IsWellFormedOriginalString();
This instance method checks if the original string used to create the `Uri` object was well-formed according to RFC 3986. It returns `true` if the URI string is well-formed; otherwise, `false`.
Example 1: Basic URI Validation
string uriString = "https://www.example.com/path?query=value";
Uri uri = new Uri(uriString);
bool isValid = uri.IsWellFormedOriginalString();
Console.WriteLine($"Is '{uriString}' well-formed? {isValid}"); // Output: True
Example 2: Validating Various URIs
public static void CheckUri(Uri uri) {
bool isValid = uri.IsWellFormedOriginalString();
Console.WriteLine($"Is '{uri}' well-formed? {isValid}");
}
public static void Main(string[] args) {
// ... (code to create and validate several URIs using CheckUri) ...
}
Example 3: URI Equality and Well-Formedness Check
Uri uri1 = new Uri("https://www.example.com/path");
Uri uri2 = new Uri("https://www.anotherexample.com/path");
// ... (code to compare uri1 and uri2 for equality and check if uri1 is well-formed using IsWellFormedOriginalString()) ...
Using `Uri.IsWellFormedOriginalString()`
Use this method to validate URIs before using them in network operations or other URI-dependent functions. This helps avoid unexpected errors.