使用C#,我很惊讶它似乎从流中保存二进制信息有多复杂。我正尝试使用WebRequest类下载PNG数据文件,但只是将生成的Stream传输到文件,而不会破坏它比我想象的更详细。首先,仅仅使用StreamReader和StreamWriter是不好的,因为ReadToEnd()函数返回一个字符串,这有效地使PNG文件的大小加倍(可能是由于UTF转换)保存流中的二进制数据
所以我的问题是,我真的有编写所有这些代码,还是有一个更干净的方式来做到这一点?
Stream srBytes = webResponse.GetResponseStream();
// Write to file
Stream swBytes = new FileStream("map(" + i.ToString() + ").png",FileMode.Create,FileAccess.Write);
int count = 0;
byte[] buffer = new byte[4096];
do
{
count = srBytes.Read(buffer, 0, buffer.Length);
swBytes.Write(buffer, 0, count);
}
while (count != 0);
swBytes.Close();
你永远不应该对待任意字节流作为字符串,但。因为他们不是。 – Joey 2010-12-12 14:21:44