I'm sorry to write in english, because there is no chinese input software in my computer in company.     
            string s = "asdfghjkl";
            Stream stream = new MemoryStream();
            StreamWriter sw = new StreamWriter(stream);
            sw.WriteLine(s);
            StreamReader sr = new StreamReader(stream);
            string str = sr.ReadToEnd();
I define a Stream and write something in it .But I can't read anything into the new string, why?
Please reply in Chinese , thanks.

解决方案 »

  1.   

    Stream要关闭以后才能再次打开读取。但你这个例子比较特殊,用MemoryStream关闭以后,不可能再被打开。实际这样使用毫无意义。你可以用FileStream试一下。
      

  2.   

    写完后关闭流,再重新new一次,用阅读器读取。
      

  3.   

    你这样当然无法读取到任何内容,因为StreamReader是从文件当前位置开始读取,而文件当前位置在写入数据后被设置到写入最后一个字节的位置,当然读不到任何数据,你要重新打开一个MemoryStream才能让文件当前位置回复到开始,而且你的StreamWriter也需要先调用Flush才会真正写入MemoryStream,光是Write只会把内容写入缓冲,没有真正写入MemoryStream,
      

  4.   

    Thanks. Another question. Now there is a currect Json Stream. I get it on the Internet service. And then if I get the data in this stream into a string with streamReader.ReadToEnd(),the data is currectly got out. Next I try to get out the data from this stream again, but use DataContractJsonSerializer and put into a object. At this time,it raise a exception. The stream is null. Following is the code:    StreamReader reader = new StreamReader(responseStream);
        string result = reader.ReadToEnd();
        DataContractJsonSerializer ser = new DataContractJsonSerializer(Result.type);
        object o = ser.ReadObject(responseStream); //this line raise a exceptionAnd if I get out the data with DataContractJsonSerializer first, then the data can be currectly got out and put into the object, next I try to get out the data with streamReader.ReadToEnd() into a string, the string is "",but there is no exception.
    The code is :    object o = ser.ReadObject(responseStream);
        DataContractJsonSerializer ser = new DataContractJsonSerializer(Result.type);
        StreamReader reader = new StreamReader(responseStream);
        string result = reader.ReadToEnd();  //the result is ""I want to know why the data lose when I get out the data the first time whatever the way I use.
    Reply in Chinese, Thanks.
      

  5.   


                string s = "asdfghjkl";
                Stream stream = new MemoryStream();
                StreamWriter sw = new StreamWriter(stream);
                sw.WriteLine(s);
    /////////加上这两句/////////
                sw.Flush();
                sw.Close;
    /////////////////////////
                StreamReader sr = new StreamReader(stream);
                string str = sr.ReadToEnd();
      

  6.   


    这个问题很简单啊,从Internet出来的Stream是单向只读的,你第一次读以后读指针就会到流的最后端了,不可能再回来。第二次肯定什么也读不到了。