440

我有一个 Web 服务器,它将大型二进制文件(几兆字节)读入字节数组。服务器可能同时读取多个文件(不同的页面请求),因此我正在寻找最优化的方法来执行此操作,而不会过多地占用 CPU。下面的代码足够好吗?

public byte[] FileToByteArray(string fileName)
{
    byte[] buff = null;
    FileStream fs = new FileStream(fileName, 
                                   FileMode.Open, 
                                   FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    long numBytes = new FileInfo(fileName).Length;
    buff = br.ReadBytes((int) numBytes);
    return buff;
}
4

12 回答 12

848

只需将整个内容替换为:

return File.ReadAllBytes(fileName);

但是,如果您担心内存消耗,则根本不应该一次将整个文件全部读入内存。你应该分块做。

于 2010-01-08T21:27:08.003 回答
78

我可能会争辩说,这里的答案通常是“不要”。除非您绝对需要一次所有数据,否则请考虑使用Stream基于 - 的 API(或阅读器/迭代器的某些变体)。当您有多个并行操作(如问题所建议的那样)以最小化系统负载和最大化吞吐量时,这一点尤其重要。

例如,如果您将数据流式传输给调用者:

Stream dest = ...
using(Stream source = File.OpenRead(path)) {
    byte[] buffer = new byte[2048];
    int bytesRead;
    while((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) {
        dest.Write(buffer, 0, bytesRead);
    }
}
于 2010-01-08T21:44:33.273 回答
36

我会这样想:

byte[] file = System.IO.File.ReadAllBytes(fileName);
于 2010-01-08T21:28:44.270 回答
34

您的代码可以考虑到这一点(代替 File.ReadAllBytes):

public byte[] ReadAllBytes(string fileName)
{
    byte[] buffer = null;
    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    {
        buffer = new byte[fs.Length];
        fs.Read(buffer, 0, (int)fs.Length);
    }
    return buffer;
} 

请注意 Integer.MaxValue - Read 方法设置的文件大小限制。换句话说,您一次只能读取 2GB 的块。

另请注意,FileStream 的最后一个参数是缓冲区大小。

我还建议阅读有关FileStreamBufferedStream的信息。

与往常一样,一个简单的示例程序来分析最快将是最有益的。

此外,您的底层硬件将对性能产生很大影响。您是否正在使用带有大缓存的基于服务器的硬盘驱动器和带有板载内存缓存的 RAID 卡?或者您使用的是连接到 IDE 端口的标准驱动器?

于 2010-01-08T21:36:57.903 回答
10

根据操作频率、文件大小和您正在查看的文件数量,还有其他性能问题需要考虑。要记住的一件事是,您的每个字节数组都将在垃圾收集器的支配下释放。如果您没有缓存任何这些数据,您最终可能会产生大量垃圾并将大部分性能损失到% Time in GC. 如果块大于 85K,您将分配到大对象堆(LOH),这将需要所有代的集合来释放(这是非常昂贵的,并且在服务器上将停止所有执行,同时它正在进行)。此外,如果 LOH 上有大量对象,最终可能会出现 LOH 碎片(LOH 永远不会压缩),这会导致性能不佳和内存不足异常。一旦达到某个点,您就可以回收该过程,但我不知道这是否是最佳实践。

关键是,在必须以最快的方式将所有字节读入内存之前,您应该考虑应用程序的整个生命周期,否则您可能会以短期性能换取整体性能。

于 2010-01-08T22:25:19.947 回答
8

我会说BinaryReader很好,但可以重构为此,而不是所有那些用于获取缓冲区长度的代码行:

public byte[] FileToByteArray(string fileName)
{
    byte[] fileData = null;

    using (FileStream fs = File.OpenRead(fileName)) 
    { 
        using (BinaryReader binaryReader = new BinaryReader(fs))
        {
            fileData = binaryReader.ReadBytes((int)fs.Length); 
        }
    }
    return fileData;
}

应该比 using 更好.ReadAllBytes(),因为我在顶部回复的评论中看到.ReadAllBytes()其中一位评论者对大于 600 MB 的文件有问题,因为 aBinaryReader是针对这类事情的。此外,将其放在using语句中可确保FileStreamandBinaryReader被关闭和处置。

于 2016-10-12T00:18:24.630 回答
2

概述:如果您的图像作为 action= 嵌入资源添加,则使用 GetExecutingAssembly 将 jpg 资源检索到流中,然后将流中的二进制数据读取到字节数组中

   public byte[] GetAImage()
    {
        byte[] bytes=null;
        var assembly = Assembly.GetExecutingAssembly();
        var resourceName = "MYWebApi.Images.X_my_image.jpg";

        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        {
            bytes = new byte[stream.Length];
            stream.Read(bytes, 0, (int)stream.Length);
        }
        return bytes;

    }
于 2020-06-15T21:45:07.483 回答
2

如果“大文件”意味着超出 4GB 限制,那么我下面的编写代码逻辑是合适的。需要注意的关键问题是与 SEEK 方法一起使用的 LONG 数据类型。因为 LONG 能够指向超过 2^32 个数据边界。在此示例中,代码首先处理 1GB 块中的大文件,在处理完整个 1GB 大块之后,处理剩余的 (<1GB) 字节。我使用此代码计算超过 4GB 大小的文件的 CRC。(在本例中使用https://crc32c.machinezoo.com/进行 crc32c 计算)

private uint Crc32CAlgorithmBigCrc(string fileName)
{
    uint hash = 0;
    byte[] buffer = null;
    FileInfo fileInfo = new FileInfo(fileName);
    long fileLength = fileInfo.Length;
    int blockSize = 1024000000;
    decimal div = fileLength / blockSize;
    int blocks = (int)Math.Floor(div);
    int restBytes = (int)(fileLength - (blocks * blockSize));
    long offsetFile = 0;
    uint interHash = 0;
    Crc32CAlgorithm Crc32CAlgorithm = new Crc32CAlgorithm();
    bool firstBlock = true;
    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    {
        buffer = new byte[blockSize];
        using (BinaryReader br = new BinaryReader(fs))
        {
            while (blocks > 0)
            {
                blocks -= 1;
                fs.Seek(offsetFile, SeekOrigin.Begin);
                buffer = br.ReadBytes(blockSize);
                if (firstBlock)
                {
                    firstBlock = false;
                    interHash = Crc32CAlgorithm.Compute(buffer);
                    hash = interHash;
                }
                else
                {
                    hash = Crc32CAlgorithm.Append(interHash, buffer);
                }
                offsetFile += blockSize;
            }
            if (restBytes > 0)
            {
                Array.Resize(ref buffer, restBytes);
                fs.Seek(offsetFile, SeekOrigin.Begin);
                buffer = br.ReadBytes(restBytes);
                hash = Crc32CAlgorithm.Append(interHash, buffer);
            }
            buffer = null;
        }
    }
    //MessageBox.Show(hash.ToString());
    //MessageBox.Show(hash.ToString("X"));
    return hash;
}
于 2019-04-26T04:16:45.373 回答
0

使用 C# 中的 BufferedStream 类来提高性能。缓冲区是内存中用于缓存数据的字节块,从而减少了对操作系统的调用次数。缓冲区提高了读写性能。

请参阅以下代码示例和其他说明:http: //msdn.microsoft.com/en-us/library/system.io.bufferedstream.aspx

于 2010-01-08T21:37:45.593 回答
0

用这个:

 bytesRead = responseStream.ReadAsync(buffer, 0, Length).Result;
于 2019-04-13T07:39:37.497 回答
-4

我建议尝试使用该Response.TransferFile()方法然后Response.Flush()Response.End()您的大文件提供服务。

于 2010-01-19T23:37:55.937 回答
-7

如果您正在处理超过 2 GB 的文件,您会发现上述方法都失败了。

将流传递给 MD5并允许它为您分块文件要容易得多:

private byte[] computeFileHash(string filename)
{
    MD5 md5 = MD5.Create();
    using (FileStream fs = new FileStream(filename, FileMode.Open))
    {
        byte[] hash = md5.ComputeHash(fs);
        return hash;
    }
}
于 2014-10-20T09:56:23.613 回答