FileStream.Read - 不使用循环读取流
FileStream.Read - Read a stream without using a loop
如何在不使用循环的情况下读取文件流?当我使用这段代码时,它只读取 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();
}
假设您的文件包含文本,那么您可以使用流 reader 并将您的 FileStream 传递给构造函数(下面我创建一个新的 FileStream 来打开文件):
using(StreamReader reader = new StreamReader(new FileStream("path", FileMode.Open)))
{
string data = reader.ReadToEnd();
}
如果您想 一次性阅读 整个 文件 ,我建议对二进制文件使用 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
来自 Stream.Read
上的 documentation:
Return Value
Type: System.Int32
The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
所以看来 Stream.Read
读取小于缓冲区长度是完全合法的,前提是它告诉你它确实做了什么。
如何在不使用循环的情况下读取文件流?当我使用这段代码时,它只读取 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();
}
假设您的文件包含文本,那么您可以使用流 reader 并将您的 FileStream 传递给构造函数(下面我创建一个新的 FileStream 来打开文件):
using(StreamReader reader = new StreamReader(new FileStream("path", FileMode.Open)))
{
string data = reader.ReadToEnd();
}
如果您想 一次性阅读 整个 文件 ,我建议对二进制文件使用 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
来自 Stream.Read
上的 documentation:
Return Value
Type: System.Int32
The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
所以看来 Stream.Read
读取小于缓冲区长度是完全合法的,前提是它告诉你它确实做了什么。