[英]How do I replace special characters in a URL?
這可能很簡單,但我自己找不到答案:(
基本上,我想要的是,給定這個字符串:
“ http://www.google.com/search?hl=en&q=c# objects”
我想要這個輸出:
http://www.google.com/search?hl=en&q=c%23+objects
我確信在框架中埋藏了一些輔助類,它可以解決這個問題,但是我找不到它。
編輯:我應該補充一點,這是一個Winforms應用程序。
HttpServerUtility.UrlEncode(串)
應該解決任何麻煩的人物
要使用它,您需要添加對System.Web的引用(Project Explorer>引用>添加引用> System.Web)
完成后,您可以使用它來編碼要添加到查詢字符串的任何項目:
System.Web.HttpUtility.UrlEncode("c# objects");
如果你不想依賴System.Web這里是我在C#OAuth庫中的“UrlEncode”的實現(需要正確的實現 - 即空格應使用百分比編碼而不是“+”用於空格等。)
private readonly static string reservedCharacters = "!*'();:@&=+$,/?%#[]";
public static string UrlEncode(string value)
{
if (String.IsNullOrEmpty(value))
return String.Empty;
var sb = new StringBuilder();
foreach (char @char in value)
{
if (reservedCharacters.IndexOf(@char) == -1)
sb.Append(@char);
else
sb.AppendFormat("%{0:X2}", (int)@char);
}
return sb.ToString();
}
@Wilfred Knievel有接受的答案,但如果你想避免依賴System.Web
命名空間,你也可以使用Uri.EscapeUriString()
。
查看Server.UrlEncode
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.