C# 如何将整个流加载到 MemoryStream 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11397565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load entire stream into MemoryStream?
提问by apocalypse
Like in the topic: I want to read data from a file (from stream) into memory (memorystream) to improve my app speed. How to do it?
就像在主题中一样:我想将文件(从流)中的数据读取到内存(内存流)中以提高我的应用程序速度。怎么做?
采纳答案by Jon Skeet
A few options:
几个选项:
Read it all into a byte array first...
首先将其全部读入字节数组...
byte[] data = File.ReadAllBytes(file);
MemoryStream stream = new MemoryStream(data);
Or use .NET 4's CopyTo method
或者使用 .NET 4 的 CopyTo 方法
MemoryStream memoryStream = new MemoryStream();
using (Stream input = File.OpenRead(file))
{
input.CopyTo(memoryStream);
}
memoryStream.Position = 0;
Or do it manually
或者手动执行
MemoryStream memoryStream = new MemoryStream();
using (Stream input = File.OpenRead(file))
{
byte[] buffer = new byte[32 * 1024]; // 32K buffer for example
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, bytesRead);
}
}
memoryStream.Position = 0;
回答by Austin Salonen
If you can hold the entire file in memory, File.ReadAllBytesshould work for you:
如果您可以将整个文件保存在内存中,File.ReadAllBytes应该适合您:
using (var ms = new MemoryStream(File.ReadAllBytes(file)))
{
// do work
}

