C# Uri Class

2023-03-02

說明如何使用 .NET Framework 的 Uri Class,簡化 URI 資源路徑的存取與使用。

logo

說明

Uri 類別的建構可以用於標準化 Uri 路徑,建構為 Uri 的類別後,會自動轉換為小寫、移除預設的 Port、移除多餘的路徑等,例如以下的 URL 處理:

new Uri(@"https://sDwh.DEV:443/Posts/../Posts/Article.html?date=20230302#Content");

// https://sdwh.dev/Posts/Article.html?date=20230302#Content

而 Uri 類別預設為 Read Only,如果想要調整可以搭配 UriBuilder 來設定。

var uri = new Uri(@"https://sDwh.DEV:443/Posts/../Posts/Article.html?date=20230302#Content");

var builder = new UriBuilder(uri);

builder.Port = 3389;
builder.Fragment = "Navbar";
builder.Host = "net.sdwh.dev";

// https://net.sdwh.dev:3389/Posts/Article.html?date=20230302#Navbar

Url

new Uri("https://sdwh.dev:443/Posts/Article.html?date=20230302#Content");
uri.Scheme
uri.Authority
uri.AbsolutePath
uri.Query
uri.PathAndQuery
uri.Port
uri.Fragment
uri.IsDefaultPort
uri.HostNameType
Property Value
Scheme https
Authority sdwh.dev
AbsolutePath /Posts/Article.html
Query ?date=20230302
PathAndQuery /Posts/Article.html?date=20230302
Port 443
Fragment #Content
IsDefaultPort True
HostNameType Dns

File UNC

new Uri(@"file://folder1/folder2/file.txt");
Property Value
Scheme file
Authority folder1
AbsolutePath /folder2/file.txt
Query
PathAndQuery /folder2/file.txt
Port -1
Fragment
IsDefaultPort True
HostNameType Dns

UNC

new Uri(@"//folder1/folder2/file.txt");
Property Value
Scheme file
Authority folder1
AbsolutePath /folder2/file.txt
Query
PathAndQuery /folder2/file.txt
Port -1
Fragment
IsDefaultPort True
HostNameType Dns

FTP

需要注意的是使用 FTP 藉由 Uri 分析,路徑斜線必須為正斜率的斜線,否則會發生路徑解析失敗的問題。

new Uri("ftp://example.com/files/filename.txt");
Property Value
Scheme ftp
Authority example.com
AbsolutePath /files/filename.txt
Query
PathAndQuery /files/filename.txt
Port 21
Fragment
IsDefaultPort True
HostNameType Dns

參考資料

Uri Class | learn.microsoft