1

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

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

1 回答 1

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();
于 2015-11-30T09:58:06.683 回答