Vinamra Bhantagar
Vinamra Bhantagar

Reputation: 147

Read exe file as binary file in C#

I want to read an exe file in my C# code then decode as base64.

I am doing it like this

FileStream fr = new FileStream(@"c:\1.exe", FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader sr = new StreamReader(fr);
fr.Read(data, 0, count);

But the problem is that when I write this file the written file gets corrupted. When analyzing in hex workshop code value 20 in hex is being replaced by 0.

Upvotes: 2

Views: 8390

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

A StreamReader should be used only with text files. With binary files you need to use directly a FileStream or:

byte[] buffer = File.ReadAllBytes(@"c:\1.exe");
string base64Encoded = Convert.ToBase64String(buffer);
// TODO: do something with the bas64 encoded string

buffer = Convert.FromBase64String(base64Encoded);
File.WriteAllBytes(@"c:\2.exe", buffer);

Upvotes: 8

Kieren Johnstone
Kieren Johnstone

Reputation: 41983

StreamReader official docs:

"Implements a TextReader that reads characters from a byte stream in a particular encoding."

It's for text, not binary files. Try just Stream or BinaryReader.. (Why did you try a StreamReader?)

Upvotes: 3

Related Questions