gpt4 book ai didi

c# - 将 pdf 转换为来自 url 的流

转载 作者:太空狗 更新时间:2023-10-29 22:23:20 26 4
gpt4 key购买 nike

我有一个 PDF 托管在 http://test.com/mypdf.pdf 中.

如何将 PDF 转换为 Stream,然后使用此 Stream 将其转换回 PDF。

我尝试了以下但出现异常(见图):

private static Stream ConvertToStream(string fileUrl)
{
HttpWebResponse aResponse = null;
try
{
HttpWebRequest aRequest = (HttpWebRequest)WebRequest.Create(fileUrl);
aResponse = (HttpWebResponse)aRequest.GetResponse();
}
catch (Exception ex)
{

}

return aResponse.GetResponseStream();
}

enter image description here

最佳答案

这将起作用:

private static Stream ConvertToStream(string fileUrl)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

try {
MemoryStream mem = new MemoryStream();
Stream stream = response.GetResponseStream();

stream.CopyTo(mem,4096);

return mem;
} finally {
response.Close();
}
}

但是,您对返回的内存流的生命周期负全部责任。

更好的方法是:

private static void ConvertToStream(string fileUrl, Stream stream)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

try {
Stream response_stream = response.GetResponseStream();

response_stream.CopyTo(stream,4096);
} finally {
response.Close();
}
}

然后您可以执行以下操作:

using (MemoryStream mem = new MemoryStream()) {
ConvertToStream('http://www.example.com/',mem);
mem.Seek(0,SeekOrigin.Begin);

... Do something else ...
}

您也可以直接返回响应流,但您必须检查它的生命周期,释放响应可能释放流,从而释放内存副本。

关于c# - 将 pdf 转换为来自 url 的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13176204/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com