将Byte []转换为PDF

时间:2010-03-16 11:53:45

标签: c# pdf bytearray

借助这个问题C# 4.0: Convert pdf to byte[] and vice versa,我能够将byte []转换为PDF。字节数组长度约为25990。当我尝试打开PDF时,它说文件已损坏。可能是什么原因?

我尝试了BinaryWriter,但它创建了0 KB的PDF。

这是来自Web服务的响应

示例代码

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

2 个答案:

答案 0 :(得分:9)

您正在从流中读取两次但只写一个缓冲区。改变这个:

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

对此:

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

答案 1 :(得分:2)

似乎你缺少一些字节,因为你有一个不必要的读取。试试这个:

  do
  {
    count = responseStream.Read(buffer, 0, buffer.Length);
    memoryStream.Write(buffer, 0, count);
  } while (count != 0);