将 pdf 转换为流的最有效方法是什么

What would be the most efficient way of converting a pdf to a stream

我有一个 WCF 服务,它将接收一个 ID 和 return 一个基于该 ID 的 pdf 文件。我假设执行此操作的最佳方法是将 pdf 文件转换为某种字符串,然后 return 它。但是,我不确定要使用哪个流 (Stream, Filestream, or MemoryStream)。

我知道我可以将 pdf 文件读取为字节数组,然后使用 MemoryStream 对其进行处理,但我觉得有更有效的方法。

我尝试按照此 post 中的建议进行操作:How to convert a pdf to a memory stream

将文件路径硬编码到 return 中,如下所示:

return File(@"C:\MyFile.pdf", "application/pdf");

只是为了看看会发生什么,但在 File 上收到错误消息:`'System.IO.File' 是一个 'type',但用法与 'variable' 类似。

谁能提供一点见解?

编辑

这是我目前正在努力的方向:

[OperationContract]
[WebInvoke(Method = "GET",
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    UriTemplate = "/GetInvoiceFile")]
Stream GetInvoiceFile(string id);

public Stream GetInvoiceFile(string BillingPeriodId)
{
    byte[] bytes = File.ReadAllBytes(@"C:\pdf-test.pdf");
    return new MemoryStream(bytes);
}

我只是不知道如何将我的 OperationContract 编辑为 return pdf。有什么想法吗?

答案取决于你有什么。您似乎将文件路径设置为 string。可能,您的 WCF 方法 returns 一个 byte[]。您需要以某种方式将该路径有效地转换为 byte[]

您可以使用 File.ReadAllBytes(string path) 执行此操作。

WCF 也支持流式写入,但有点复杂,而且对于小文件的性能提升值得怀疑。

您尝试指定 MIME 类型 ("application/pdf") 的事实告诉我您并不真正理解 WCF 服务和 HTTP 服务之间的区别。研究这个是你的功课。