How to load entire stream into MemoryStream?

后端 未结 2 1435
轮回少年
轮回少年 2020-12-14 08:00

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?

相关标签:
2条回答
  • 2020-12-14 08:13

    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

    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;
    
    0 讨论(0)
  • 2020-12-14 08:13

    If you can hold the entire file in memory, File.ReadAllBytes should work for you:

    using (var ms = new MemoryStream(File.ReadAllBytes(file)))
    {
        // do work
    }
    
    0 讨论(0)
提交回复
热议问题