You receive an unhandled exception error message when you use the MemoryStream class in the .NET Framework 1.1 Service Pack 1 (888226)



The information in this article applies to:

  • Microsoft .NET Framework 1.1 Service Pack 1 (SP1)

SYMPTOMS

When you try to use the MemoryStream class to read a memory stream in a Microsoft Visual C# .NET 2003 project, you may receive an error message that is similar to one of the following:
Unhandled Exception: System.Xml.XmlException: The root element is missing.
Unhandled Exception: System.IO.SomeStreamException: The memory stream is at the end of the buffer.
Unhandled Exception: System.IO.SomeReaderException: The reader cannot read anymore.

CAUSE

This behavior occurs if the following conditions are true:
  • You install the Microsoft .NET Framework 1.1 Service Pack 1 (SP1).
  • The memory stream is positioned at the end-of-stream.

WORKAROUND

To work around this behavior, reset the stream position before you create the XmlTextReader class. For an example, see the "More Information" section.

MORE INFORMATION

Steps to reproduce the behavior

  1. Create a text file that is named Output.txt, and then paste the following code in Output.txt:
    <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body><HelloWorldResponse xmlns="http://tempuri.org/">
    <HelloWorldResult>SUCCESS:test</HelloWorldResult></HelloWorldResponse></soap:Body></soap:Envelope>
  2. In Visual C# .NET, create a new Console Application project. By default, Class1.cs is created.
  3. Paste the following code in the Class1.cs file:
    using System;
    using System.IO;
    using System.Text;
    using System.Xml;
    
    public class Form1
    {
    	static void Main() 
    	{
    		try
    		{
    
    			Stream _oldStream = new FileStream(@"Output.txt", FileMode.Open, FileAccess.Read);
    			Stream _newStream = new MemoryStream();
    
    			TextReader tr = new StreamReader(_oldStream);
    			TextWriter tw = new StreamWriter(_newStream);
    			tw.WriteLine(tr.ReadToEnd());
    			tw.Flush();
    
    			XmlReader reader = new XmlTextReader( new StreamReader( _newStream ) );
    			_newStream.Position = 0;
    			_newStream.Seek( 0, SeekOrigin.Begin );
    			reader.Read();
    
    			while( reader.Read() );
    
    			Console.WriteLine("Success");
    		}
    		catch (Exception ex)
    		{
    			System.Diagnostics.Debug.WriteLine(ex.ToString());
    			Console.WriteLine("Exception : " + ex.Message + "\n" + ex.StackTrace);
    		}
    	}
    }
  4. Compile and then run the application.

Modification Type:MajorLast Reviewed:11/24/2004
Keywords:kbAppDev kbProgramming kbtshoot kbprb KB888226 kbAudDeveloper