打开dcoument时,将字节数组转换为pdf会引发错误

时间:2015-11-30 09:02:11

标签: c# wcf pdf bytestream

我正在开发一个WCF服务,它从互联网门户网站下载pdf文件,将其转换为字节数组并将其发送到客户端。在客户端,我使用WriteAllBytes方法将此字节数组转换为pdf。但是在打开pdf文档时,它会显示“打开documnet时出错。文件可能已损坏或损坏”

WCF代码 //

FileInformation fileInfo = File.OpenBinaryDirect(clientContext, fileRef.ToString());

 byte[] Bytes = new byte[Convert.ToInt32(fileSize)]; 
fileInfo.Stream.Read(Bytes, 0, Bytes.Length); 
return Bytes; 

客户代码

byte[] recievedBytes = <call to wcf method returing byte array>;
                File.WriteAllBytes(path, recievedBytes);

1 个答案:

答案 0 :(得分:3)

我强烈怀疑这是问题所在:

byte[] Bytes = new byte[Convert.ToInt32(fileSize)]; 
fileInfo.Stream.Read(Bytes, 0, Bytes.Length); 

您假设只需拨打一次Read即可阅读所有内容。相反,你应该循环,直到你 读取所有内容。例如:

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

可替换地:

MemoryStream output = new MemoryStream((int) fileSize];
fileInfo.Stream.CopyTo(output);
return output.ToArray();
相关问题