I am developing a WCF service that downloads a pdf file from a internet portal converts it into byte array and sends it to the client. On client side i am converting this byte array to pdf by using WriteAllBytes method. But while opening the pdf document it displays "There is error while opening the documnet. The file might be damaged or corrupted"
WCF Code //
FileInformation fileInfo = File.OpenBinaryDirect(clientContext, fileRef.ToString());
byte[] Bytes = new byte[Convert.ToInt32(fileSize)];
fileInfo.Stream.Read(Bytes, 0, Bytes.Length);
return Bytes;
Client code
byte[] recievedBytes = <call to wcf method returing byte array>;
File.WriteAllBytes(path, recievedBytes);
I strongly suspect this is the problem:
byte[] Bytes = new byte[Convert.ToInt32(fileSize)];
fileInfo.Stream.Read(Bytes, 0, Bytes.Length);
You're assuming a single call to Read
will read everything. Instead, you should loop round until you have read everything. For example:
byte[] bytes = new byte[(int) fileSize];
int index = 0;
while (index < bytes.Length)
{
int bytesRead = fileInfo.Stream.Read(bytes, index, bytes.Length - index);
if (bytesRead == 0)
{
throw new IOException("Unable to read whole file");
}
index += bytesRead;
}
Alternatively:
MemoryStream output = new MemoryStream((int) fileSize];
fileInfo.Stream.CopyTo(output);
return output.ToArray();
See more on this question at Stackoverflow