System.Io.Stream怎么重复利用

mylocoy 2008-05-18 04:41:55
myPostResponse =(HttpWebResponse)myPostRequest.GetResponse();
System.IO.Stream stream = myPostResponse.GetResponseStream(); //这里得到返回请求的stream

因为要对这个stream执行编码识别和后来的保存数据的操作,

//下面开始自动识别编码
byte[] buf = new byte[1024] ;
......省略部分

while( (length=stream.Read(buf,0,buf.Length)) != 0) { //读取stream分析编码


获取到编码后后面需要 sr = new System.IO.StreamReader(stream, this._encoding);
按得到的编码保存数据
但这个stream不支持查找操作,stream.Position不能移回0,请问分析完编码后如何才能保存这个stream到文件?
...全文
529 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
niening314 2012-02-18
  • 打赏
  • 举报
回复
哈哈 跟我一样的问题哦,刚刚无意中试出来了

HttpWebRequest webrq = (HttpWebRequest)WebRequest.Create(uri);
webrq.Method = "GET";
webrq.AutomaticDecompression = DecompressionMethods.GZip;
webrq.Timeout = 50000;
HttpWebResponse webrp = (HttpWebResponse)webrq.GetResponse();
StreamReader reader = new StreamReader(webrp.GetResponseStream());//不指定编码类型
string html = reader.ReadToEnd();

之前我老是喜欢画蛇添足 如:

StreamReader reader = new StreamReader(webrp.GetResponseStream(),编码类型);

其实不用指定编码类型,系统会自动用使用正确的编码类型;
反正我试了 10多个url
都ok

具体原理不晓得是StreamReader能自动匹配编码,还是能自动读取页面流中的charset

环境 vs2008 framework 3.5
pikapi 2008-05-19
  • 打赏
  • 举报
回复
MSDN的原话是:“流可以支持查找。查找是对流内的当前位置进行查询和修改。查找功能取决于流具有的后备存储区类型。例如,网络流没有当前位置的统一概念,因此一般不支持查找。”

不知道你是要编码,还是保存这个Stream信息,如果是保存的话,还是自己写个类来存储一下。
mylocoy 2008-05-19
  • 打赏
  • 举报
回复
现在只有保存到变量里使用了。。
zhoufoxcn 提供的方法可以借鉴,但ContentEncoding和CharacterSet判断出来的编码不可靠,各个服务器不一定返回获返回正确的
周公 2008-05-19
  • 打赏
  • 举报
回复

HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

Console.WriteLine("The encoding method used is: " + myHttpWebResponse.ContentEncoding);
Console.WriteLine("The character set used is :" + myHttpWebResponse.CharacterSet);
Encoding encoding = Encoding.GetEncoding( myHttpWebResponse.ContentEncoding );
StreamReader reader= new System.IO.StreamReader(stream, encoding);
purple_tide 2008-05-19
  • 打赏
  • 举报
回复
既然这个流没法做Seek操作
那就在读取的时候 直接把值保存到某个变量 等待之后使用吧
周公 2008-05-19
  • 打赏
  • 举报
回复
利用
HttpWebResponse.CharacterSet——获取响应的字符集。
HttpWebResponse.ContentEncoding——获取用于对响应体进行编码的方法。

这两个方法获取编码,这样就可以直接用你的办法了。
sr = new System.IO.StreamReader(stream, this._encoding);
ericzhangbo1982111 2008-05-19
  • 打赏
  • 举报
回复
MemoryStream m=new MemoryStream(byte[] data);
mylocoy 2008-05-18
  • 打赏
  • 举报
回复
还是不行,
System.IO.BufferedStream bs = new System.IO.BufferedStream(stream);
这样得到的bs的CanSeek属性还是false,bs也无法进行Seek操作
starts_2000 2008-05-18
  • 打赏
  • 举报
回复
用这个处理吧
System.IO.BufferedStream bs = new System.IO.BufferedStream(stream);
mylocoy 2008-05-18
  • 打赏
  • 举报
回复
Seek和直接Position操作一样
System.Exception Message显示:此流不支持查找操作。
starts_2000 2008-05-18
  • 打赏
  • 举报
回复
stream.Seek(0, System.IO.SeekOrigin.Begin);

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧