473,769 Members | 3,857 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Find and Replace in Binary File

Newbie here. How do I do a find and replace in a binary file? I need
to read in a binary file then replace a string "ABC" with another
string "XYZ" then write to a new file. Find string is the same length
as Replace string. Here's what I have so far. I spent many hours
googling for sample code but couldn't find much. Thanks...

public static void FindReplace(str ing OldFile, string NewFile)
{
string sFind = "ABC"; //I probably need to convert these
to a byte array
string sReplace = "XYZ"; //but I don't know how.
int i;
FileStream fin = new FileStream(OldF ile, FileMode.Open);
FileStream fout = new FileStream(NewF ile,
FileMode.Create );
do
{
i = fin.ReadByte();
if (i != -1)
{
//I think I need to compare the byte being read in
//to the 1st sFind byte array here. If it matches
then
//store the position and compare the next byte.
//If all 3 bytes match then replace with sReplace
byte array.
//I'm just not sure how to do it.
fout.WriteByte( (byte)i);
}
} while (i != -1);
fin.Close();
fout.Close();
}
Feb 24 '08 #1
3 14570
I have done this before. The approach I took was to read the file bytes
into memory (because the files I was working with were small), move the
file out of the way, and then write a new file replacing the "find"
bytes with the "replace" bytes. So similar to your approach.

Here's a snippet from what I wrote (it was in 1.1 and was just "quick
and dirty" code):

ArrayList newBytes = new ArrayList(bytes .Length);
int ndx = 0;

for (int x = 0; x < bytes.Length; x++) // bytes is the original files bytes
{
if (bytes[x] == findBytes[ndx]) // findBytes is a byte[] from the
"find" string
{
if (ndx == findBytes.Lengt h - 1)
{
for (int y = 0; y < replaceBytes.Le ngth; y++) //
replaceBytes is a byte[] from the "replace" string
{
newBytes.Add(re placeBytes[y]);
}
ndx = 0;
}
else
{
ndx++;
}
}
else
{
if (ndx 0)
{
for (int y = 0; y < ndx; y++)
{
newBytes.Add(fi ndBytes[y]);
}
}
ndx = 0;
newBytes.Add(by tes[x]);
}
}

ndx is used to keep track of which byte in the findBytes should be
compared to the original files byte.

mo*****@yahoo.c om wrote:
Newbie here. How do I do a find and replace in a binary file? I need
to read in a binary file then replace a string "ABC" with another
string "XYZ" then write to a new file. Find string is the same length
as Replace string. Here's what I have so far. I spent many hours
googling for sample code but couldn't find much. Thanks...

public static void FindReplace(str ing OldFile, string NewFile)
{
string sFind = "ABC"; //I probably need to convert these
to a byte array
string sReplace = "XYZ"; //but I don't know how.
int i;
FileStream fin = new FileStream(OldF ile, FileMode.Open);
FileStream fout = new FileStream(NewF ile,
FileMode.Create );
do
{
i = fin.ReadByte();
if (i != -1)
{
//I think I need to compare the byte being read in
//to the 1st sFind byte array here. If it matches
then
//store the position and compare the next byte.
//If all 3 bytes match then replace with sReplace
byte array.
//I'm just not sure how to do it.
fout.WriteByte( (byte)i);
}
} while (i != -1);
fin.Close();
fout.Close();
}
Feb 24 '08 #2
Thanks for all your comments. Here's what I'm trying to mimic in
VB6. I guess .NET is more restrictive in what type of file you can do
find/replace. Sounds too difficult in C# so I might just have to
revert back to VB6 for this one. Thanks...

Sub FindRplace()
Dim sBuffer As String
Dim ff As Integer
ff = FreeFile
Open txtFile.Text For Binary As #ff
sBuffer = Space$(LOF(ff))
Get #ff, 1, sBuffer
Close #ff
sBuffer = Replace(sBuffer , "ABC", "XYZ")
Open txtNew.Text For Binary As #ff
Put #ff, , sBuffer
Close #ff
End Sub
Feb 25 '08 #3
On Mon, 25 Feb 2008 11:56:50 -0800, <mo*****@yahoo. comwrote:
Thanks for all your comments. Here's what I'm trying to mimic in
VB6. I guess .NET is more restrictive in what type of file you can do
find/replace. Sounds too difficult in C# so I might just have to
revert back to VB6 for this one.
It's not difficult in C#. The code would not even be significantly
different from the VB6 code you posted, other than the lack of a
short-hand "replace" feature for dealing with byte arrays (which you
should be able to easily write yourself). And your VB6 code has all the
same problems we've warned that could come up doing it in C#.

But if you've already got VB6 code to do what you want, maybe you should
just stick with that if you'd rather not use the suggestions offered here.

Pete
Feb 25 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
33679
by: hokieghal99 | last post by:
import os, string print " " setpath = raw_input("Enter the path: ") def find_replace(setpath): for root, dirs, files in os.walk(setpath): fname = files for fname in files: find = string.find(file(os.path.join(root,fname), 'rb').read(), 'THIS') print find
1
3729
by: Xah Lee | last post by:
suppose you want to do find & replace of string of all files in a directory. here's the code: ©# -*- coding: utf-8 -*- ©# Python © ©import os,sys © ©mydir= '/Users/t/web'
19
2935
by: rbt | last post by:
Here's the scenario: You have many hundred gigabytes of data... possible even a terabyte or two. Within this data, you have private, sensitive information (US social security numbers) about your company's clients. Your company has generated its own unique ID numbers to replace the social security numbers. Now, management would like the IT guys to go thru the old data and replace as many SSNs with the new ID numbers as possible. You...
6
3292
by: Jon Slaughter | last post by:
I'm trying to replace some bytes in a file using fstream but all I seem to be able to do is append or 0 the file then write... Basicaly I just need to replace the first 512 bytes of the file with some buffer(but eventually I will need to replace random blocks in the file at different locations). Is there anyway to do this efficiently using fstream? (I know I can duplicate the file, but it seems a waste to rewrite the same data for no...
8
4065
by: Eric Lilja | last post by:
Hello, I had what I thought was normal text-file and I needed to locate a string matching a certain pattern in that file and, if found, replace that string. I thought this would be simple but I had problems getting my algorithm to work and in order to help me find the solution I decided to print each line to screen as I read them. Then, to my surprise, I noticed that there was a space between every character as I outputted the lines to the...
3
9040
by: Mullin Yu | last post by:
I have a file, and want to replace some bytes by other bytes e.g. Old: 1b 25 New: 1b 26 66 31 30 30 59 1b 26 66 58 How to implement? Thanks!
0
3081
by: Xah Lee | last post by:
Interactive Find and Replace String Patterns on Multiple Files Xah Lee, 2006-06 Suppose you need to do find and replace of a string pattern, for all files in a directory. However, you do not want to replace all of them. You need to look at it in a case-by-case basis. What can you do? Answer: emacs.
23
439
by: Umesh | last post by:
This is a basic thing. Say A=0100 0001 in ASCII which deals with 256 characters(you know better than me!) But we deal with only four characters and 2 bits are enough to encode them. I want to confirm if we can encode A in 2bits(say 00), B in 2 bits (01), C in 2 bits(10) and D in 2 bits by some program. I only use this four alphabet in my work. Can u pl write a sample program to reach my goal?
40
3120
by: niskin | last post by:
Hi I'm trying to open up a .jpg file in binary mode using C and replace it with another .jpg file. This is my code so far: #include <stdio.h> #include <stdlib.h> int main() { FILE *background; background=fopen( "c:\\Dave\\C-programming\\stbedes.jpg", "w+b" ); FILE *newpic;
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10212
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10047
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3962
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.