Replace & with & in C#

If you really want to go that route, you have to assign the result of Replace (the method returns a new string because strings are immutable) back to the variable:

value = value.Replace("&", "&");

I would suggest rethinking the way you're writing your XML though. If you switch to using the XmlTextWriter, it will handle all of the encoding for you (not only the ampersand, but all of the other characters that need encoded as well):

using(var writer = new XmlTextWriter(@"C:\MyXmlFile.xml", null))
{
    writer.WriteStartElement("someString");
    writer.WriteText("This is < a > string & everything will get encoded");
    writer.WriteEndElement();
}

Should produce:

<someString>This is &lt; a &gt; string &amp; 
    everything will get encoded</someString>

You should really use something like Linq to XML (XDocument etc.) to solve it. I'm 100% sure you can do it without all your WriteLine´s ;) Show us your logic?

Otherwise you could use this which will be bullet proof (as opposed to .Replace("&")):

var value = "hej&hej<some>";
value = new System.Xml.Linq.XText(value).ToString(); //hej&amp;hej&lt;some&gt;

This will also take care of < which you also HAVE TO escape :)

Update: I have looked at the code for XText.ToString() and internally it creates a XmlWriter + StringWriter and uses XNode.WriteTo. This may be overkill for a given application so if many strings should be converted, XText.WriteTo would be better. An alternative which should be fast and reliant is System.Web.HttpUtility.HtmlEncode.

Update 2: I found this System.Security.SecurityElement.Escape(xml) which may be the fastest and ensures max compatibility (supported since .Net 1.0 and does not require the System.Web reference).


you can also use HttpUtility.HtmlEncode class under System.Web namespace instead of doing the replacement yourself. here you go: http://msdn.microsoft.com/en-us/library/73z22y6h.aspx

Tags:

C#

String