4

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.

Maxqueue
  • 2,194
  • 2
  • 23
  • 55
  • `System.Security.SecurityElement.FromString()` doesn't return a `string` yet you assign its result to a `string`; is that a typo? – cliesens Dec 12 '19 at 01:13
  • Yes i meant to put .Text at end. Thanks for catching – Maxqueue Dec 12 '19 at 01:18
  • The `FromString` method expects XML; e.g. `string unEscapedString = System.Security.SecurityElement.FromString($"{escapedString}");` – quaabaam Dec 12 '19 at 01:24
  • It just seem odd that they have escape function that takes any string but not the reverse. – Maxqueue Dec 12 '19 at 01:26
  • The `FromString` is there to get a `SecurityElement` object from a string of XML, not to Unescape the value to a string. So, technically there is no _decode_ in the 'SecurityElement' object. It makes sense there would be a helper method to encode the value but not to decode it as you would be wanting the `SecurityElement` object to work with. – quaabaam Dec 12 '19 at 01:50
  • @Maxqueue Side note: you probably doing something wrong altogether... like constructing XML with string concatenation... You may want to stop for a second and think if there is better approach to achieve what you actually need... – Alexei Levenkov Dec 12 '19 at 01:58

1 Answers1

7

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;
Rufus L
  • 36,127
  • 5
  • 30
  • 43