Converting & to & etc

C#Html EncodeString Conversion

C# Problem Overview


I want to convert & to &, " to " etc. Is there a function in c# that could do that without writing all the options manually?

C# Solutions


Solution 1 - C#

System.Web.HttpUtility.HtmlDecode()

Edit: Note from here that "To encode or decode values outside of a web application, use..."

System.Net.WebUtility.HtmlDecode()

Solution 2 - C#

Use the static method

HttpUtility.HtmlEncode

to change & to & and " to ". Use

HttpUtility.HtmlDecode

to do the reverse.

Solution 3 - C#

You can use System.Net.WebUtility.HtmlDecode(uri);

Solution 4 - C#

using System.Web; 
...
var html = "this is a sample & string"; 
var decodedhtml = HttpUtility.HtmlDecode(html);

Solution 5 - C#

Solution 6 - C#

For .NET < 4 simple encoder

	public static string HtmlEncode(string value)
	{
		return value.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");
	}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser189370View Question on Stackoverflow
Solution 1 - C#Matt HamsmithView Answer on Stackoverflow
Solution 2 - C#Ian KempView Answer on Stackoverflow
Solution 3 - C#Corredera RomainView Answer on Stackoverflow
Solution 4 - C#Alex W.View Answer on Stackoverflow
Solution 5 - C#RichardODView Answer on Stackoverflow
Solution 6 - C#Bartosz WójcikView Answer on Stackoverflow