写入字符串流和回读不工作 [英] Writing String to Stream and reading it back does not work

查看:114
本文介绍了写入字符串流和回读不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要写一个字符串流(在这种情况下,一个MemoryStream)和读取的字节数一个接一个。

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 uniEncoding = new UnicodeEncoding();
String message = "Message";

stringAsStream.Write(uniEncoding.GetBytes(message), 0, message.Length);

Console.WriteLine("This:\t\t" + (char)uniEncoding.GetBytes(message)[0]);
Console.WriteLine("Differs from:\t" + (char)stringAsStream.ReadByte());



(不需要的)结果我得到的是:

The (undesired) result I get is:

This:         M
Differs from: ?



它的看起来的喜欢它没有被正确读取,作为第一个字符消息是'M',从UnicodeEncoding实例中获取字节的时候,但不读他们从流回来时,它的工作原理。

It looks like it's not being read correctly, as the first char of "Message" is 'M', which works when getting the bytes from the UnicodeEncoding instance but not when reading them back from the stream.

我在做什么错了?

的大局观:我有一个算法,将流的字节工作,我想作为一般地和工作与任何流。我想一个ASCII字符串转换成一个MemoryStream,或者使用另一种方法能够对字符串作为流工作。有问题的算法可工作于流的字节数。

The bigger picture: I have an algorithm which will work on the bytes of a Stream, I'd like to be as general as possible and work with any Stream. I'd like to convert an ASCII-String into a MemoryStream, or maybe use another method to be able to work on the String as a Stream. The algorithm in question will work on the bytes of the Stream.

推荐答案

在你写的的MemoryStream 键,你读它回来之前,你需要寻找回到开头的的MemoryStream 所以你没有结束阅读。

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.

更新

在看到您的更新,我认为有建立流的更可靠的方式:

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();
    }
}



正如你所看到的,该代码使用一个StreamWriter来写整个字符串(用正确的编码)输出到的MemoryStream 。这需要的烦恼中解脱出来,确保了被写入字符串的整个字节数组

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.

这篇关于写入字符串流和回读不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆