在文件中的特定位置插入字节的正确方法是什么?C#



我有一个文件:out.txt

out.txt包含行:

123456789

我们需要编写一个程序,以便在文件的某个位置插入新的数字
例如:在第3位插入数字2000。该文件应具有以下结果:

1232000456789

程序限制!不能从文件中缓存行。也就是说,文件的重量可能高达约40 GB,甚至更大。因此,您需要以某种方式将缓冲区插入到所需的位置。并将其余部分移动插入字符长度的长度

这是坏掉的代码。它替换字符。剩下的数据消失了:

using (FileStream fileStream = new FileStream(oldFileForUpdate, FileMode.OpenOrCreate, FileAccess.Write))
{
foreach (KeyValuePair<long, byte[]> keyValuePair in fileStructExtension.Buffer)
{
fileStream.Seek(keyValuePair.Key, SeekOrigin.Begin);
await fileStream.WriteAsync(keyValuePair.Value, 0, keyValuePair.Value.Length, cancellationToken);
}
}

您最好的选择是将数据复制到一个临时文件中,如下所示:

  1. 将插入点之前的所有字节复制到临时文件
  2. 将要插入的字节复制到临时文件中
  3. 将剩余的字节从原始文件复制到临时文件
  4. 删除原始文件
  5. 将临时文件重命名为原始文件

示例实现(根据口味调整缓冲区大小(:

public static void Insert(string filename, long offset, byte[] data)
{
byte[] buffer = new byte[32768];
var tempFile = filename + ".tmp";
using (var input = File.OpenRead(filename))
using (var output = File.OpenWrite(tempFile))
{
while (offset > 0)
{
int n = (int)Math.Min(offset, buffer.Length);
n = input.Read(buffer, 0, n);
if (n <= 0)
throw new InvalidOperationException("Input file is too short.");
output.Write(buffer, 0, n);
offset -= n;
}
output.Write(data, 0, data.Length);
input.CopyTo(output);
}
File.Delete(filename);
File.Move(tempFile, filename);
}

当然,这需要您可以在与源文件夹相同的文件夹中创建一个临时文件,并且有足够的可用磁盘空间用于临时文件和原始文件。

相关内容

最新更新