在記錄檔案位置或資源路徑時,有時候會避免儲存絕對路徑, 而改以取得相對路徑,方便在不同環境執行。 在 C# 中,可以使用以下方法: ## 步驟 取得完整路徑與根路徑 ```csharp string fullPath = "C:\\Project\\App\\images\\file.jpg"; string rootPath = "C:\\Project\\App\\"; ``` 將路徑轉為 Uri 物件 ```csharp Uri fullPathUri = new Uri(fullPath); Uri rootPathUri = new Uri(rootPath); ``` 透過 MakeRelativeUri 方法取得相對路徑 ```csharp Uri relativeUri = rootPathUri.MakeRelativeUri(fullPathUri); ``` 將 Uri 轉回字串格式 ```csharp string relativePath = relativeUri.ToString(); Console.WriteLine(relativePath); // 結果: images/file.jpg ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up