Reputation: 31
I want to read data from exe file. On java i read exe perfect from start to end, bun on c# i cannot read all file. File lenth is true but in result show only head of exe file
string fileLoc = filePaths[0];
FileStream fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
foreach(byte b in bin){
Console.Write((char)b);
}
fs.Close();
output is only the head of exe: MZP
Upvotes: 1
Views: 1723
Reputation: 941
Cannot reproduce:
string fileLoc = //my path to git.exe
FileStream fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
foreach (byte b in bin)
{
Console.Write((char)b);
}
fs.Close()
It writes all data from it.
But i see many problems in your code:
1) never do work with files with such unsafer way (if error occured file will not close) rewrite:
string fileLoc = //my path to git.exe
using(FileStream fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read)) {
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
foreach (byte b in bin)
{
Console.Write((char)b);
}
} // no more explicit close required, but it will closed with guarantee
2) not mistake but in C# it's preferable use var (analoug to auto in c++)
using(var fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read)) {
var br = new BinaryReader(fs);
var bin = br.ReadBytes(Convert.ToInt32(fs.Length));
foreach (var b in bin)
{
Console.Write((char)b);
}
} //it still strong typed, but type referenced only once at right side of assigment
3) Not require use Convert for explicitly castable types (long->int)
var bin = br.ReadBytes((int)fs.Length);
4) I don't know why only MZP is written in your case, but can imagine that if you cast byte to char you will get many not-printable symbols including \r \n \f and so on in output - how your concrete terminal will be react? - i don't know
5) If you print (char)b just for test of bin
- why so badly - why you not simply test bin.Length or why you print (char)b
and not b+" "
? Otherwise if you really want to print bytes to console - it's bad idea anyway - look (4)
6) Why BinaryReader? if you just want read all
using(var fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read)) {
var bin = new byte[(int)fs.Length];
// u can use usual stream pattern
int l=0; while((l+=fs.Read(bin,t,bin.Length-t))<bin.Length);
foreach (var b in bin)
{
Console.Write((char)b);
}
}
Upvotes: 1