tags:

views:

630

answers:

2

How to convert pdf to byte[] and vice versa?

+5  A: 
byte[] bytes = System.IO.File.ReadAllBytes("myfile.pdf");

System.IO.File.WriteAllBytes("myfile.pdf", bytes);
John JJ Curtis
its not working. it returns {byte[0]}
xscape
What's the size of your pdf file?
John JJ Curtis
Jeff, thank you. Its working.
xscape
A: 

Easiest way:

byte[] buffer;
using (Stream stream = new IO.FileStream("file.pdf"))
{
   buffer = new byte[stream.Length - 1];
   stream.Read(buffer, 0, buffer.Length);
}

using (Stream stream = new IO.FileStream("newFile.pdf"))
{
   stream.Write(buffer, 0, buffer.Length);
}

Or something along these lines...

Paulo Santos
You forgot to take care ot the return value of the Read method. You have to loop the reading and read until you actually get all the data.
Guffa
@Guffa not quite, if you take a look I've used `stream.Length` that returns the length of the ENTIRE file stream, hence reading the file as a whole, not only as chunk of data.
Paulo Santos
@Paulo: You are missing the point. Even if you request the entire stream from the Read method, it doesn't have to read the entire stream. It will read one byte or more, and return how many bytes were actually read. If you ignore the return value of the Read method, you may only get part of the file.
Guffa