Writing String to Stream and reading it back does not work

后端 未结 5 1082
死守一世寂寞
死守一世寂寞 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:39

    I think it would be a lot more productive to use a TextWriter, in this case a StreamWriter to write to the MemoryStream. After that, as other have said, you need to "rewind" the MemoryStream using something like stringAsStream.Position = 0L;.

    stringAsStream = new MemoryStream();
    
    // create stream writer with UTF-16 (Unicode) encoding to write to the memory stream
    using(StreamWriter sWriter = new StreamWriter(stringAsStream, UnicodeEncoding.Unicode))
    {
      sWriter.Write("Lorem ipsum.");
    }
    stringAsStream.Position = 0L; // rewind
    

    Note that:

    StreamWriter defaults to using an instance of UTF8Encoding unless specified otherwise. This instance of UTF8Encoding is constructed without a byte order mark (BOM)

    Also, you don't have to create a new UnicodeEncoding() usually, since there's already one as a static member of the class for you to use in convenient utf-8, utf-16, and utf-32 flavors.

    And then, finally (as others have said) you're trying to convert the bytes directly to chars, which they are not. If I had a memory stream and knew it was a string, I'd use a TextReader to get the string back from the bytes. It seems "dangerous" to me to mess around with the raw bytes.

提交回复
热议问题