System.OverflowException: 数组维度超过了支持的范围。

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
FileStream fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1);
ZipEntry entry = new ZipEntry(tempfile);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
outstream.PutNextEntry(entry);
outstream.Write(buffer, 0, buffer.Length);

日志:

[2023-09-25 15:21:23.196 +08:00] [ERR] 文件压缩失败!

文件:H:\slpk\345slpk\

System.OverflowException: 数组维度超过了支持的范围。

在 cim_dgp.Common.DirectoryUtil.ZipCompress(String strFile, ZipOutputStream outstream, String staticFile) 位置 E:\project\wuchuan\code\cim-dgp\cim_dgp\cim_dgp.Common\DirectoryHelper\DirectoryUtil.cs:行号 594

在 cim_dgp.Common.DirectoryUtil.DirectoryZip(String strFile, String strZip) 位置 E:\project\wuchuan\code\cim-dgp\cim_dgp\cim_dgp.Common\DirectoryHelper\DirectoryUtil.cs:行号 559

问题定位:

byte[] buffer = new byte[fs.Length];

原因:

文件过大时,使用文件流长度创建数组,内存溢出;

解决:分块读取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string relativePath = Path.GetRelativePath(rootFolder, file);
using (FileStream fs = File.OpenRead(file))
{
ZipEntry entry = new ZipEntry(relativePath)
{
DateTime = DateTime.Now,
Size = fs.Length
};
zipStream.PutNextEntry(entry);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
zipStream.Write(buffer, 0, bytesRead);
}
}