gpt4 book ai didi

C# 将文件拆分为两个字节数组

转载 作者:太空宇宙 更新时间:2023-11-03 19:43:30 25 4
gpt4 key购买 nike

因为字节数组的最大值是 2GB,假设我有一个更大的文件,我需要将它转换为字节数组。由于我不能保存整个文件,我应该如何将其转换为两个?

我试过:

long length = new System.IO.FileInfo(@"c:\a.mp4").Length;
int chunkSize = Convert.ToInt32(length / 2);


byte[] part2;
FileStream fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
try
{
part2 = new byte[chunkSize]; // create buffer
fileStream.Read(part2, 0, chunkSize);
}
finally
{
fileStream.Close();
}

byte[] part3;
fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
try
{
part3 = new byte[chunkSize]; // create buffer
fileStream.Read(part3, 5, (int)(length - (long)chunkSize));
}
finally
{
fileStream.Close();
}

但它不起作用。

有什么想法吗?

最佳答案

您可以使用StreamReader 读取file too large to read into a byte array

const int max = 1024*1024;

public void ReadALargeFile(string file, int start = 0)
{
FileStream fileStream = new FileStream(file, FileMode.Open,FileAccess.Read);
using (fileStream)
{
byte[] buffer = new byte[max];
fileStream.Seek(start, SeekOrigin.Begin);
int bytesRead = fileStream.Read(buffer, start, max);
while(bytesRead > 0)
{
DoSomething(buffer, bytesRead);
bytesRead = fileStream.Read(buffer, start, max);
}
}
}

关于C# 将文件拆分为两个字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49559731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com