gpt4 book ai didi

c# - 优化文件分割

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

您好,我目前使用以下代码将文件拆分为多个 2mb 的较小部分。

const int BUFFER_SIZE = 20 * 1024;
byte[] buffer = new byte[BUFFER_SIZE];

using (Stream input = File.OpenRead(inputFile)) {
int index = 0;
while (input.Position < input.Length) {
using (Stream output = File.Create(path)) {
int remaining = chunkSize, bytesRead;
while (remaining > 0 && (bytesRead = input.Read(buffer, 0,
Math.Min(remaining, BUFFER_SIZE))) > 0) {
output.Write(buffer, 0, bytesRead);
remaining -= bytesRead;
}
}
}
index++;
}

这非常有效,可以将一个 10mb 的文件拆分为 5 x 2mb 的文件 0.part、2.part 等...

我想知道如何在知道 chunkSize 始终保持在 2mb 的情况下再次生成第 3 部分。我可以通过包装在一个 if,else 中并评估索引来实现这一点,但是对于一个 1GB 的文件,这个过程可能需要一段时间才能循环。我想更深入地了解此功能以及如何才能获取我需要的文件部分?

最佳答案

input.Position属性是可设置的。如果您知道需要第 3 部分,请将 Position 设置为 2*chunkSize 以跳过前两个 block ,并执行最内层的 while 循环一次从该位置复制到输出:

int desiredChunkNumber = 3;
using (Stream input = File.OpenRead(inputFile)) {
input.Position = (desiredChunkNumber - 1) * chunkSize;
using (Stream output = File.Create(path)) {
int remaining = chunkSize, bytesRead;
while (remaining > 0 && (bytesRead = input.Read(buffer, 0,
Math.Min(remaining, BUFFER_SIZE))) > 0) {
output.Write(buffer, 0, bytesRead);
remaining -= bytesRead;
}
}
}

关于c# - 优化文件分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36425726/

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