"'\f', hexadecimal value 0x0C, is an invalid character" — Can't clean it
<p>I'm getting the dreaded "'\f', hexadecimal value 0x0C, is an invalid character" when attempting to save my Xdocument content to file. </p>

<p>I've Googled it and i've attempted to clean it by converting the Xdocument to string cleans it of non-ascii characters (see below). The method to do this I copied from another poster.</p>

<p>It's now throwing the exception where i try to pass the string to the cleaning method though. It doesn't seem to want to cast to string. I tried just outputting to a text fie so i could see what the problem character was, but it then threw the exception there. Any ideas please?</p>

<pre><code>public void combineContentXmlWithS1000Dtemplate(XElement content)
{

    XDocument XDoc = XDocument.Load(GlobalVars.pathToDMshells + "\\descript.xml" );

    content.Descendants("para").Where(e =&gt; string.IsNullOrEmpty(e.Value)).Remove(); // remove all empty para elements

    XDoc.XPathSelectElement("/dmodule/content").Add(content); // adds the new tree to the S1000D template XML

    writeHeaderData(XDoc);

    //System.IO.File.WriteAllText(GlobalVars.pathToOutput + "\\Log.text", XDoc.ToString()); // It even threw exception here

    string cleanedXML = CleanInvalidXmlChars(XDoc.ToString()); // clean the doc of non ascii characters
    XDocument FinishedDM = XDocument.Parse(cleanedXML);

    saveMyS1000Dfile(FinishedDM);
}

public static string CleanInvalidXmlChars(string StrInput)
{
    //Returns same value if the value is empty.
    if (string.IsNullOrWhiteSpace(StrInput))
    {
        return StrInput;
    }
    // From xml spec valid chars:
    // #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]    
    // any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
    string RegularExp = @"[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]";
    return Regex.Replace(StrInput, RegularExp, String.Empty);
}
</code></pre>