C# 类库中的 HtmlEncode
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1144535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HtmlEncode from Class Library
提问by Villager
I have a class library (in C#). I need to encode my data using the HtmlEncode method. This is easy to do from a web application. My question is, how do I use this method from a class library that is being called from a console application?
我有一个类库(在 C# 中)。我需要使用 HtmlEncode 方法对我的数据进行编码。这很容易从 Web 应用程序中完成。我的问题是,如何从控制台应用程序调用的类库中使用此方法?
采纳答案by Russ Bradberry
Import System.Web Or call the System.Web.HttpUtility which contains it
导入 System.Web 或调用包含它的 System.Web.HttpUtility
You will need to add the reference to the DLL if it isn't there already
如果 DLL 不存在,您将需要添加对 DLL 的引用
string TestString = "This is a <Test String>.";
string EncodedString = System.Web.HttpUtility.HtmlEncode(TestString);
回答by Irwin
Just reference the System.Web assembly and then call: HttpServerUtility.HtmlEncode
只需引用 System.Web 程序集,然后调用:HttpServerUtility.HtmlEncode
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.htmlencode.aspx
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.htmlencode.aspx
回答by AnthonyWJones
Add a reference to System.Web.dll and then you can use the System.Web.HtmlUtility class
添加对 System.Web.dll 的引用,然后您可以使用 System.Web.HtmlUtility 类
回答by Dan Diplo
If you are using C#3 a good tip is to create an extension method to make this even simpler. Just create a static method (preferably in a static class) like so:
如果您使用的是 C#3,一个很好的提示是创建一个扩展方法来使这更简单。只需创建一个静态方法(最好在静态类中),如下所示:
public static class Extensions
{
public static string HtmlEncode(this string s)
{
return HttpUtility.HtmlEncode(s);
}
}
You can then do neat stuff like this:
然后你可以做这样的整洁的事情:
string encoded = "<div>I need encoding</div>".HtmlEncode();
回答by George Chakhidze
System.Net.WebUtility
class is
available starting from .NET 4.0
(You don?t need System.Web.dll dependency).
System.Net.WebUtility
类从 .NET 4.0 开始可用(您不需要 System.Web.dll 依赖项)。
回答by Jonx
In case you are working with silverlight, use this:
如果您正在使用 Silverlight,请使用以下命令:
System.Windows.Browser.HttpUtility.HtmlEncode(...);
回答by Koen Zomers
In case you're using SharePoint 2010, using the following line of code will avoid having to reference the whole System.Web library:
如果您使用的是 SharePoint 2010,则使用以下代码行将避免引用整个 System.Web 库:
Microsoft.SharePoint.Utilities.SPHttpUtility.HtmlEncode(stringToEncode);
回答by Palanikumar
Try this
尝试这个
System.Net.WebUtility.HtmlDecode(string);
System.Net.WebUtility.HtmlEncode(string);