文件流定位时报错:试图将文件指针移到文件开头之前。

Code:

1
2
3
4
5
6
7
8
9
10
11
byte[] fileContentByte;
if (totalChunk == curChunk)
{
var temp = new FileInfo(filePath).Length - (totalChunk - 1) * BYTES_PER_CHUNK;
fileContentByte = new byte[temp];
}
else
fileContentByte = new byte[BYTES_PER_CHUNK];
// position 类型 int
fs.Seek(position, SeekOrigin.Begin);
fs.Read(fileContentByte, 0, fileContentByte.Length);

日志:

[2023-09-26 11:21:29.244 +08:00] [INF] PostUtil.cs UploadFormdataWithParaAsync:47 上传切片文件: 1024 / 5559
[2023-09-26 11:21:29.247 +08:00] [ERR] BigFileHelper.cs UploadFile:369 文件上传错误!
试图将文件指针移到文件开头之前。

在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
在 System.IO.FileStream.SeekCore(Int64 offset, SeekOrigin origin)
在 System.IO.FileStream.Seek(Int64 offset, SeekOrigin origin)
在 cim_dgp.BigFile.BigFileHelper.UploadChunkFile(String filePath, Int32 position, FileStream fs, Int32 totalChunk, Int32 curChunk, String guid) 位置 E:\project\wuchuan\code\cim-dgp\cim_dgp\cim_dgp\BigFile\BigFileHelper.cs:行号 389
在 cim_dgp.BigFile.BigFileHelper.UploadFile(UploadFileModel uploadFile, String location, Action1 actionMessage, Func3 funcProgress) 位置 E:\project\wuchuan\code\cim-dgp\cim_dgp\cim_dgp\BigFile\BigFileHelper.cs:行号 263

问题定位:

在 System.IO.FileStream.Seek(Int64 offset, SeekOrigin origin)

原因:

FileStream.Seek 定位时使用了int类型数值,溢出后会变成负数!

解决:

1
2
3
4
5
6
7
8
9
10
11
byte[] fileContentByte;
if (totalChunk == curChunk)
{
var temp = new FileInfo(filePath).Length - (totalChunk - 1) * BYTES_PER_CHUNK;
fileContentByte = new byte[temp];
}
else
fileContentByte = new byte[BYTES_PER_CHUNK];
// position 类型改用 long
fs.Seek(position, SeekOrigin.Begin);
fs.Read(fileContentByte, 0, fileContentByte.Length);