从指定位置的文件中替换一些文本 [英] replace some text from file at specified position

查看:71
本文介绍了从指定位置的文件中替换一些文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我已经创建的bin文件。我想将一些文本从指定位置替换为给定长度。并将其更新为现有文件。

就像我的文件名是applicationdata.bin。我想打开这个文件,想要替换一些字节,然后将其更新为同一个文件。

i Have a bin file that i have already created. i want to replace some text from specified position to given length. and update it into existing file.
like my file name is applicationdata.bin. i want to open this file and want to replace some bytes and then update it into same file.

推荐答案

这只是用 BinaryReader在 [ ^ ],然后替换您想要更改的部分,并使用 BinaryWriter 写出来。您可以这样做:



  • 读取要更改的部分。
  • 将其写入输出
  • 写入新数据。
  • 在输入文件中跳过要替换的数据。
  • 读取输入文件的其余部分。
  • 将该数据写入输出文件。
This is just a matter of reading the file with a BinaryReader[^], then replace the parts that you want changed, and write it out with a BinaryWriter. You could do it like this:

  • Read up to the part to be changed.
  • Write that to the output file.
  • Write the new data.
  • Skip past the data to be replaced in the input file.
  • Read the remainder of the input file.
  • Write that data to the output file.


读取文件,在内存中修改其内容,然后将其写回磁盘。
Read the file, modify its content in memory and then write it back to the disk.


根据文件的大小,有两种方法可以做到这一点:

1)如果它相对较小(小于2GB且较小)更好的是你可以读取整个文件,将其拆分为要替换的部分和之后的部分,然后将它们与新数据一起重新绑定并将其写回:

Depending on the size of the file, there are two ways you can do this:
1) If it is relatively small (less than 2GB and the smaller the better) you can read the whole file in, split it into the bit before the part to replace and the part after, then bolt them back together with the new data and write it back:
byte[] orig = File.ReadAllBytes(@"D:\Temp\Myfile.bin");
int lengthOfStart = 100;
int lengthOfUnwanted = 10;
byte[] start = new byte[lengthOfStart];
byte[] end = new byte[orig.Length - (lengthOfStart + lengthOfUnwanted)];
Array.Copy(orig, start, lengthOfStart);
Array.Copy(orig, lengthOfStart + lengthOfUnwanted, end, 0, end.Length);
byte[] newData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 };
byte[] outp = new byte[start.Length + newData.Length + end.Length];
Array.Copy(start, outp, start.Length);
Array.Copy(newData, 0, outp, start.Length, newData.Length);
Array.Copy(end, 0, outp, start.Length + newData.Length, end.Length);
File.WriteAllBytes(@"D:\Temp\newFile.bin", outp);



2)如果它很大,则以块的形式读取它,将每个块写入一个新文件,直到找到要替换的位。读取要更换的块并将其丢弃。写下新数据。以块的形式读取文件的其余部分,并在出发时将它们写入新文件。


2) If it is large, then read it in chunks, writing each chunk to a new file as you go until you get to the bit to replace. Read the chunk to replace and discard it. Write the new data. Read the remainder of the file in chunks, and write them to the new file as you go.


这篇关于从指定位置的文件中替换一些文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆