title: C# - From NetworkStream to XElement managing different encoding
body: <p>I've an application that search XML over the network (using TcpClient), these XML have various encoding (one site in UTF8, other in Windows-1252). I would like encode all of these XML in UTF-8 (always) to be sure I'm clean.</p>
  
  <p>How can I do the conversion from the NetworkStream to an XElement encoding correctly all data?</p>
  
  <p>I've this :</p>
  
  <pre><code>NetworkStream _clientStream = /* ... */;
  MemoryStream _responseBytes = new MemoryStream();
  
  // serverEncoding -&gt; Xml Encoding I get from server
  // _UTF8Encoder -&gt; Local encoder (always UTF8)
  
  try
  {
      _clientStream.CopyTo(_responseBytes);
  
      if (serverEncoding != _UTF8Encoder)
      {
          MemoryStream encodedStream = new MemoryStream();
          string line = null;
          using (StreamReader reader = new StreamReader(_responseBytes))
          {
              using (StreamWriter writer = new StreamWriter(encodedStream))
              {
                  while ((line = reader.ReadLine()) != null)
                  {
                      writer.WriteLine(
                          Encoding.Convert(serverEncoding, _UTF8Encoder, serverEncoding.GetBytes(line))
                          );
                  }
              }
          }
          _responseBytes = encodedStream;
      }
  
      _responseBytes.Position = 0;
      using (XmlReader reader = XmlReader.Create(_responseBytes))
      {
          xmlResult = XElement.Load(reader, LoadOptions.PreserveWhitespace);
      }
  }
  catch (Exception ex)
  { }
  </code></pre>
  
  <p>Have you a better solution (and by ignoring all '\0' ?).</p>
  
  <hr>
  
  <h2>Edit</h2>
  
  <p>This works :</p>
  
  <pre><code>byte[] b = _clientStream.ReadToEnd();
  var text = _UTF8Encoder.GetString(b, 0, b.Length);
  xmlResult = XElement.Parse(text, LoadOptions.PreserveWhitespace);
  </code></pre>
  
  <p>But this not :</p>
  
  <pre><code>using (var reader = new StreamReader(_clientStream, false))
      xmlResult = XElement.Load(reader, LoadOptions.PreserveWhitespace);
  </code></pre>
  
  <p>I don't understand why ...</p>