Click here to Skip to main content
15,903,854 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted

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.
 
Share this answer
 
Read the file, modify its content in memory and then write it back to the disk.
 
Share this answer
 
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:
C#
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) 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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900