通常我会使用:
HttpContext.Current.Server.UrlEncode("url");
Run Code Online (Sandbox Code Playgroud)
但由于这是一个控制台应用程序,HttpContext.Current所以总会如此null.
还有另一种方法可以使用我可以使用的相同方法吗?
Ost*_*ati 78
试试这个!
Uri.EscapeUriString(url);
Run Code Online (Sandbox Code Playgroud)
要么
Uri.EscapeDataString(data)
Run Code Online (Sandbox Code Playgroud)
无需参考System.Web.
编辑:请参阅另一个 SO答案了解更多......
And*_*lor 72
我不是.NET的人,但是,你不能使用:
HttpUtility.UrlEncode Method (String)
Run Code Online (Sandbox Code Playgroud)
这里描述的是:
MSDN上的HttpUtility.UrlEncode方法(字符串)
t3r*_*rse 13
Ian Hopkins的代码为我提供了诀窍,无需添加对System.Web的引用.对于那些不使用VB.NET的人来说,这是一个C#的端口:
/// <summary>
/// URL encoding class. Note: use at your own risk.
/// Written by: Ian Hopkins (http://www.lucidhelix.com)
/// Date: 2008-Dec-23
/// (Ported to C# by t3rse (http://www.t3rse.com))
/// </summary>
public class UrlHelper
{
public static string Encode(string str) {
var charClass = String.Format("0-9a-zA-Z{0}", Regex.Escape("-_.!~*'()"));
return Regex.Replace(str,
String.Format("[^{0}]", charClass),
new MatchEvaluator(EncodeEvaluator));
}
public static string EncodeEvaluator(Match match)
{
return (match.Value == " ")?"+" : String.Format("%{0:X2}", Convert.ToInt32(match.Value[0]));
}
public static string DecodeEvaluator(Match match) {
return Convert.ToChar(int.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber)).ToString();
}
public static string Decode(string str)
{
return Regex.Replace(str.Replace('+', ' '), "%[0-9a-zA-Z][0-9a-zA-Z]", new MatchEvaluator(DecodeEvaluator));
}
}
Run Code Online (Sandbox Code Playgroud)
你会想要使用
System.Web.HttpUtility.urlencode("url")
Run Code Online (Sandbox Code Playgroud)
确保将system.web作为项目中的引用之一.我不认为它在控制台应用程序中默认包含在参考中.