private static void DoDetectEncoding(Encoding encoding, string testPattern) { using (MemoryStream stream = new MemoryStream()) using (StreamWriter writer = new StreamWriter(stream, encoding)) { writer.Write(testPattern); writer.Flush(); // detect encoding stream.Position = 0; Encoding detected = StreamUtility.DetectBestEncoding(stream); Assert.IsNotNull(detected); Assert.AreEqual(encoding.CodePage, detected.CodePage); // use encoding to read stream using (WrappingStream wrappingStream = new WrappingStream(stream, Ownership.None)) using (StreamReader reader = new StreamReader(wrappingStream, detected, false)) { string read = reader.ReadToEnd(); Assert.AreEqual(testPattern, read); } } }