通常我只会使用:
HttpContext.Current.Server.UrlEncode("url");
但由于这是一个控制台应用程序,因此HttpContext.Current
将始终为null
。
有没有其他方法可以用来做同样的事情呢?
发布于 2008-08-18 14:51:07
我不是.NET的人,但是,你不能使用:
HttpUtility.UrlEncode Method (String)
具体描述如下:
发布于 2010-10-24 09:25:41
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));
}
}
发布于 2008-08-18 14:53:22
你会想要使用
System.Web.HttpUtility.urlencode("url")
确保将system.web作为项目中的引用之一。我不认为它默认包含在控制台应用程序中作为引用。
https://stackoverflow.com/questions/14731
复制相似问题