Question

How Do I read values from Binary file and Write to a new Binay file?

Asked by: rangers99

Im developing a Windows application using Visual C# and Visual Studio 2008.

I have a huge binary file that contains millions of items of data of type short. Lets say the file is called "original.dat"

I want to open this file and access the data. I want to do a simple arithmetic operation to the data (lets say add 10) and then store the amended data in a new file called "newfile.dat"

Can someone post the code that lets me do this?

Note the file is so big that loading it in its entirety into memory and then doing the arithmetic operation is not an option.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-04 at 06:14:53ID24870849
Topics

C# Programming Language

,

.NET

Participating Experts
3
Points
215
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. binary
    I would like the source for a program that would take the binary (yes, the 1's and 0's) from a file and save it as a text file then also take a text file of 1's and 0's and make it back into a file. I hope I made it clear what I'm looking for if its not just ask.
  2. binary
    What is the fastest way to insert a record with binary data in TQuery ? Andrew
  3. binary
    How can I convert text to it's binary value? WITH VISUAL BASIC
  4. binary search
    Hi, How to write a binary search in Delphi? It should only search an array of already sorted integers. Please one recursively and one using a loop. (with explanations) Regards Phi

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: slightwvPosted on 2009-11-04 at 06:26:36ID: 25739537

Not sure what the problem is.  Just read the file in chunks.

http://www.dotnet4all.com/dotnet-code/2004/11/binary-file-io-using-methods-of.html

 

by: sedgwickPosted on 2009-11-04 at 06:52:49ID: 25739849

f u read binary data, what kind of arithmetic operation ur trying to do?
adding 10 to what data?

 

by: InternalStaticPosted on 2009-11-04 at 07:35:51ID: 25740342

First off, all files are technically binary data. Some binary data is just interpreted differently depending on the context. For instance, if I have a text file that contains the word "Test", you won't find the letters 'T', 'e', 's', and 't' on your hard drive anywhere. You'll see a series of binary values corresponding to those letters depending on the encoding you use. Opening the file and treating it as text allows you to view it as text, even if it wasn't. I could open notepad, write a bunch of crap, and save it as a .dat, and it would still have the same binary data as any txt.

If the file is too fat to load all at once, you'll have to load it a chunk at a time (I suggest loading it like 1KB or so at a time, then discarding that data. I forgot how big a sector is nowadays, but that's a different story). Anyways, you could use the BinaryReader and BinaryWriter classes to make your life a tiny bit easier with this (though they're not necessary; they just make "writing binary" (I put that in quotes because, really, what else can you write to a file? Nothing. Just binary, every time).

Anyways, I'm not 100% sure I understand your question. Your "binary file", as you call it, has a bunch of binary in it, I've gathere that much (once again, I ask you, what else could it contain?). You are also saying that the binary within it should be interpreted as a very large series of short integers (ie 16-bit integers). I'm going to assume, for my solution to you, that you wish to add 10 to each short value in this file, and write the 'result' to the other file.

I really do hope this isn't homework, as I don't condone cheating, but here you go. For this example, I'm just going to read one short at a time for simplicity's sake. I suggest that you optimize it yourself (consider this my challenge to you :) ), though you don't have to, of course. Depending on the size of the file, the code I provide should be pretty slow after a certain point (then again, .NET likes to buffer file data without your knowing anyway, so it doesn't make much of a difference, if your file isn't too big...). However, the code should handle any amount of data.

Let me know if you have any questions, but as for optimizing it for you, that's up to you (unless you get it started and I see that you put some geniune effort into it. I may help you out in that case).

Hope it helps,

Nate

void RenameThisMethodRangers99()
{
//#error Ranger99: RENAME THIS METHOD. Then, remove this line.
    using (FileStream origFile = File.OpenRead("original.dat"))
    using (FileStream newFile = File.OpenWrite("newfile.dat"))
    {
        BinaryReader read = new BinaryReader(origFile);
        BinaryWriter write = new BinaryWriter(newFile);
 
        write.Write((Int16)(read.ReadInt16() + 10));
    }
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

Select allOpen in new window

 

by: rangers99Posted on 2009-11-04 at 07:50:27ID: 25740523

I had to laugh when your first comment was "not sure what the problem is".

Anyway thanks for the link. The link you gave shows an example for date of type byte. ie. the input.Read() function requires a byte array. My data is of type short. Do I simply use a factor of 2 for read (and write) to accoutn for the fact 2 bytes is equivalent to 1 short?

 

by: slightwvPosted on 2009-11-04 at 07:54:56ID: 25740574

At least I made you laugh.  ;)

I'm afraid your last question is a little to deep in the weeds for my level of programming.  I'd say try it and see or let one of our real programmer experts help.

 

by: rangers99Posted on 2009-11-04 at 07:57:49ID: 25740613

Thanks Static I'll peruse your reply and get back to you.

But Im  left wondering what this site is all about. I aks a question and Im supposed to get an answer and award points right?.

SlightWv starts off by saying "not sure what the problem is" as though he's a bit annoyed. Thats funny enough but then you start wondering whether Im cheating on my homework and then set me a few challenges.

Anyway keep up the comedy guys.

 

by: slightwvPosted on 2009-11-04 at 08:52:11ID: 25741277

Your synopsis about the site is correct.  We're here to assist in any way we can to solve your issue.

I apologize if you thought I was annoyed.  The commentary was addressing what I thought was a pretty simple question that could have been found with a simple google search.

 

by: InternalStaticPosted on 2009-11-04 at 19:23:00ID: 25746507

>> The commentary was addressing what I thought was a pretty simple question that could have been found with a simple google search.

Ehh, yes and no. Binary data scares most people, as most don't really understand it, so I guess I can't blame him. I've certainly seen much, much worse questions, oh lord... Hell, I could pick out like 40 within the first 60 questions. Anyways, most would be surprised to hear that fetching a Byte (8 bits) from RAM actually entails telling the RAM to give you 32 bits of information, padding on the extra 24 bits for you. Binary knowledge isn't common, but I suppose it isn't rare, either. .NET is one of the "languages" in which it is forgiveable to know little about deep details.

As for converting bytes to other data types, rangers99, it's extremely easy in .NET. There are a few ways to do it; however, the easiest one is to use the static class called "BitConverter" in the System namespace. For example, to convert bytes to an Int16 (aka short) using BitConverter, you call the BitConverter.ToInt16 method. You could grab a hunk of your data (an even number, probably something like 1024 bytes or some other power of 2) as a Byte array and pass it to the BitConverter.ToInt16 method with the necessary offset.

As well as using this class, you could just shift left and OR the two bytes you want to "merge" (ie ((Int16)(leftByte << 8)) | ((Int16)rightByte). I can't remember if .NET upcasts operands of bitwise operators to Int32 by default, but I'm too lazy to check, and casting them to Int16 shows your intent anyway (even if it does look a little strange).

I surely hope you're not cheating on your homework, as the number of borderline retarded programmers on the market is already astonishing. I don't know how much more if it I can take, so please, learn your profession, and learn it well. Cheating never helps ;)

Hope it helps,

Nate

 

by: InternalStaticPosted on 2009-11-04 at 19:24:34ID: 25746514

Heh, yeah, about the awful "questions" on EE... Check this beauty out.

Moderators: Sorry, I had to do it.

 

by: rangers99Posted on 2009-11-05 at 03:58:03ID: 31649976

IDIOTS

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...