title: How to best detect encoding in XML file?
body: <p>To load XML files with arbitrary encoding I have the following code:</p>
  
  <pre><code>Encoding encoding;
  using (var reader = new XmlTextReader(filepath))
  {
      reader.MoveToContent();
      encoding = reader.Encoding;
  }
  
  var settings = new XmlReaderSettings { NameTable = new NameTable() };
  var xmlns = new XmlNamespaceManager(settings.NameTable);
  var context = new XmlParserContext(null, xmlns, "", XmlSpace.Default, 
      encoding);
  using (var reader = XmlReader.Create(filepath, settings, context))
  {
      return XElement.Load(reader);
  }
  </code></pre>
  
  <p>This works, but it seems a bit inefficient to open the file twice. Is there a better way to detect the encoding such that I can do:</p>
  
  <ol>
  <li>Open file</li>
  <li>Detect encoding</li>
  <li>Read XML into an XElement</li>
  <li>Close file</li>
  </ol>