Stream 读取文件
Stream 要保存为文件,得借助 FileStream。
using (FileStream fs = new FileStream(path, FileMode.Create))
{
byte[] bytes = new byte[stream.Length];
int numBytesRead = 0;
int numBytesToRead = (int)stream.Length;
stream.Position = 0;
while (numBytesToRead > 0)
{
int n = stream.Read(bytes, numBytesRead, Math.Min(numBytesToRead, int.MaxValue));
if (n <= 0)
{
break;
}
fs.Write(bytes, numBytesRead, n);
{
byte[] bytes = new byte[stream.Length];
int numBytesRead = 0;
int numBytesToRead = (int)stream.Length;
stream.Position = 0;
while (numBytesToRead > 0)
{
int n = stream.Read(bytes, numBytesRead, Math.Min(numBytesToRead, int.MaxValue));
if (n <= 0)
{
break;
}
fs.Write(bytes, numBytesRead, n);
//string ss=System.Text.Encoding.Default.GetString(bytes,numBytesRead,n);//测试
numBytesRead += n;
numBytesToRead -= n;
}
fs.Close();
}
numBytesRead += n;
numBytesToRead -= n;
}
fs.Close();
}
将 Stream 依次读取到 FileStream,就可以了。
要注意,开头不要忘了将 stream.Position 置为 0。
偏移量和长度超出数组的界限,或者计数大于从索引到源集合结尾处的元素数量。
出现这种错误,常见的问题有:
- 没有将 bytes 的长度设置为 stream 的长度;
- Read 的第三个参数值超出可读取值。这个容易被忽略,因为我们常常没有考虑到,这个值加上偏移量不能超出 bytes 的范围。
更简单的用法
内容不大时,也可一次性读完:stream.Read(bytes, 0, (int)stream.Length);。
浙公网安备 33010602011771号