title: How to properly encode XML File in C#
body: <p>I have this code to return XML to a user in a web browser.</p>
  
  <pre><code>public FileResult GetReportParameters(string reportId)
  {
      string parameters = "&lt;?xml version=\"1.0\" encoding=\"UTF-16\"?&gt;\r\n" +
          LoadXml(reportId).ToString();
  
      return File(System.Text.Encoding.Unicode.GetBytes(parameters), "application/xml");
  }
  </code></pre>
  
  <p>LoadXML loads XML froma database and returns it as an XElement object.  Strings in C# are UTF-16.  So to make sure everything stays encoded correctly I specified UTF-16 for the encoding and used the Unicode encoding to convert the text to a byte[] array for the File constructor.</p>
  
  <p>When I run this from Visual Studio it works fine and displays in IE's XML visualizer.  However, after I publish this to our web server it doesn't work and IE gives the following error.</p>
  
  <blockquote>
    <p>The XML page cannot be displayed  Cannot view XML input using XSL
    style sheet. Please correct the error and then click the Refresh
    button, or try again later. </p>
    
    <hr>
    
    <p>A name was started with an invalid character. Error processing
    resource</p>
  </blockquote>
  
  <p>I was able to get it to display in IE's XML visuallizer by using UTF-8 instead.</p>
  
  <pre><code>public FileResult GetReportParameters(string reportId)
  {
      string parameters = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\r\n" +
          LoadXml(reportId).ToString();
  
      return File(System.Text.Encoding.UTF8.GetBytes(parameters), "application/xml");
  }
  </code></pre>
  
  <p>However, won't any unicode characters be displayed wrong?  What is the correct way for doing this?</p>
  
  <p>Thanks</p>