Writing String to Stream and reading it back does not work

后端 未结 5 1077
死守一世寂寞
死守一世寂寞 2020-12-30 18:54

I want to write a String to a Stream (a MemoryStream in this case) and read the bytes one by one.

stringAsStream = new MemoryStream();
UnicodeEncoding uniEn         


        
5条回答
  •  我在风中等你
    2020-12-30 19:37

    After you write to the MemoryStream and before you read it back, you need to Seek back to the beginning of the MemoryStream so you're not reading from the end.

    UPDATE

    After seeing your update, I think there's a more reliable way to build the stream:

    UnicodeEncoding uniEncoding = new UnicodeEncoding();
    String message = "Message";
    
    // You might not want to use the outer using statement that I have
    // I wasn't sure how long you would need the MemoryStream object    
    using(MemoryStream ms = new MemoryStream())
    {
        var sw = new StreamWriter(ms, uniEncoding);
        try
        {
            sw.Write(message);
            sw.Flush();//otherwise you are risking empty stream
            ms.Seek(0, SeekOrigin.Begin);
    
            // Test and work with the stream here. 
            // If you need to start back at the beginning, be sure to Seek again.
        }
        finally
        {
            sw.Dispose();
        }
    }
    

    As you can see, this code uses a StreamWriter to write the entire string (with proper encoding) out to the MemoryStream. This takes the hassle out of ensuring the entire byte array for the string is written.

    Update: I stepped into issue with empty stream several time. It's enough to call Flush right after you've finished writing.

提交回复
热议问题