views:

438

answers:

2

Hello All,

With help of this question C# 4.0: Convert pdf to byte[] and vice versa i was able to convert byte[] to PDF. Byte array length is 25990 approx. When i try to open the PDF it says file is corrupted. What could be the reason?

I tried the BinaryWriter but it creates PDF of 0 KB.

It's a response from a Web Service

Sample Code

WebResponse resp = request.GetResponse();
var buffer = new byte[4096];
Stream responseStream = resp.GetResponseStream();
{
  int count;
  do
  {
    count = responseStream.Read(buffer, 0, buffer.Length);
    memoryStream.Write(buffer, 0, responseStream.Read(buffer, 0, buffer.Length));
  } while (count != 0);
}
resp.Close();
byte[] memoryBuffer = memoryStream.ToArray();
System.IO.File.WriteAllBytes(@"E:\sample1.pdf", memoryBuffer);
int s = memoryBuffer.Length;

BinaryWriter binaryWriter = new BinaryWriter(File.Open(@"E:\sample2.pdf", FileMode.Create));
binaryWriter.Write(memoryBuffer);
+1  A: 

It seems your missing some bytes there because you have one unnecessary read. Try this:

  do
  {
    count = responseStream.Read(buffer, 0, buffer.Length);
    memoryStream.Write(buffer, 0, count);
  } while (count != 0);
bruno conde
+8  A: 

You are reading twice from the stream but only writing one buffer. Change this:

count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, responseStream.Read(buffer, 0, buffer.Length));

To this:

count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, count);
Greg Beech
Thats Great! SO Rocks!
Sri Kumar