如何在不使用循环的情况下读取文件流?当我使用这段代码时,它只读取 5714 字节而不是 1048576 字节
byte[] Buffer = new byte[1048576];
ByteSize = downloadstream.Read(Buffer, 0,Buffer.Lenght);
如果我使用这个循环,它工作正常
while ((ByteSize = downloadstream.Read(Buffer, 0, Buffer.Length)) > 0)
{
//write stream to file
}
那么我如何在不使用循环的情况下读取整个流呢? 谢谢,将不胜感激任何帮助。 我必须将所有数据读入缓冲区然后写入。抱歉,我之前没有提到这一点。
编辑:您也可以使用此代码一次将流读入缓冲区:
using (var streamreader = new MemoryStream())
{
stream.CopyTo(streamreader);
buffer = streamreader.ToArray();
}
最佳答案
如果您想一次性读取整个文件,我建议对二进制文件使用File.ReadAllBytes
:
byte[] data = File.ReadAllBytes(@"C:\MyFile.dat");
File.ReadAllText
/File.ReadAllLines
用于文本:
string text = File.ReadAllText(@"C:\MyFile.txt");
string[] lines = File.ReadAllText(@"C:\MyOtherFile.txt");
编辑:在网络的情况下
byte[] data;
using (WebClient wc = new WebClient()) {
wc.UseDefaultCredentials = true; // if you have a proxy etc.
data = wc.DownloadData(myUrl);
}
当 myUrl
是 @"https://www.google.com"
我有 data.Length == 45846
关于c# - FileStream.Read - 不使用循环读取流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38919584/