开发者

Read exe file as binary file in C#

开发者 https://www.devze.com 2023-04-06 15:12 出处:网络
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);

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.


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);


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?)

0

精彩评论

暂无评论...
验证码 换一张
取 消