Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape and unescape invalid characters

This should be really easy. I have a string that i escape like the following:

string originalString = "M&M";
string escapedString = System.Security.SecurityElement.Escape(originalString);//M&M

Good so far

string unEscapedString = System.Security.SecurityElement.FromString(escapedString).Text;

Expecting to go back to M&M but getting "object not set"

Assuming string should be in xml format so any help on what i should do in this case would be helpful.

like image 210
Maxqueue Avatar asked Oct 20 '25 07:10

Maxqueue


1 Answers

You can use System.Net.WebUtility class's static HtmlDecode method to do this:

string original = "M&M";
string escaped = System.Security.SecurityElement.Escape(original);
string unescaped = System.Net.WebUtility.HtmlDecode(escaped);

The reason the code isn't working as you have it is because the FromString method expects valid xml. See the documentation here:

Parameters
xml String
The XML-encoded string from which to create the security element.

You can make your code sample work if you add xml tags around the string:

string unescaped = SecurityElement.FromString($"<x>{escaped}</x>").Text;
like image 166
Rufus L Avatar answered Oct 22 '25 22:10

Rufus L