![](/img/trans.png)
[英]System.Uri fails to give correct AbsolutePath and LocalPath if the Path contains “#”
[英]Uri.AbsolutePath messes up path with spaces
在WinApp中,我只是試圖從Uri對象獲取絕對路徑:
Uri myUri = new Uri(myPath); //myPath is a string
//somewhere else in the code
string path = myUri.AbsolutePath;
如果我的原始路徑中沒有空格,則可以正常工作。 如果那里有空格,則字符串將被整齊; 例如,“文檔和設置”變為“ Documents%20and%20Setting”等。
任何幫助,將不勝感激!
編輯: LocalPath而不是AbsolutePath做到了!
這就是應該的樣子。 這就是所謂的URL編碼。 之所以適用,是因為URL中不允許使用空格。
如果要返回包含空格的路徑,則必須調用以下命令:
string path = Server.URLDecode(myUri.AbsolutePath);
您不需要導入任何內容即可在Web應用程序中使用它。 如果出現錯誤,請嘗試導入System.Web.HttpServerUtility。 或者,您可以這樣稱呼它:
string path = HttpContext.Current.Server.URLDecode(myUri.AbsolutePath);
它按照其應有的方式對其進行編碼,您可能會對其進行UrlDecode以便將其取回,但它並不是“被纏住”的,而是經過正確編碼的。
我不確定您在寫什么,但是要在asp.net中將其轉換回Server.UrlDecode(path)。 如果它是Windows應用程序,則還可以使用LocalPath,而不是AbsolutePath。
只需使用uri.LocalPath代替
Uri還具有幾個靜態方法-EscapeDataString和EscapeUriString。
Uri.EscapeDataString(uri.AbsolutePath)
也可以
使用HttpUtility:
HttpUtility.UrlDecode(uri.AbsolutePath)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.