/// <summary> /// Performs a test that `ReadDelimitedDataFrom` can read the same data back as was written in various different encodings. /// </summary> public void TestReadDelimitedDataFrom() { //Unicode string string testString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890!@#$%^&*()_+-="; int testStringLength = testString.Length; //With every encoding in the system foreach (var encodingInfo in System.Text.Encoding.GetEncodings()) { //Create a new memory stream using (var ms = new System.IO.MemoryStream()) { //Get the encoding var encoding = encodingInfo.GetEncoding(); System.Console.WriteLine("Testing: " + encoding.EncodingName); //Create a writer on that same stream using a small buffer using (var streamWriter = new System.IO.StreamWriter(ms, encoding, 1, true)) { //Get the binary representation of the string in the encoding being tested var encodedData = encoding.GetBytes(testString); //Cache the length of the data int encodedDataLength = encodedData.Length; //Write the value in the encoding streamWriter.Write(testString); //Ensure in the stream streamWriter.Flush(); //Go back to the beginning ms.Position = 0; string actual; int read; //Ensure that was read correctly using the binary length and not the string length //(should try to over read) if (false != EncodingExtensions.ReadDelimitedDataFrom(encoding, ms, null, encodedDataLength, out actual, out read)) { throw new System.Exception("ReadDelimitedDataFrom failed."); } //Ensure the position if (ms.Position > encodedDataLength + encoding.GetPreamble().Length) { throw new System.Exception("Stream.Position is not correct."); } //Ensure the strings are equal (The extra byte is spacing) int difference = string.Compare(encoding.GetString(encoding.GetBytes(testString)), actual); if (difference != 0 && difference > 1) { throw new System.Exception("string data is incorrect."); } Console.WriteLine(actual); } } } }