.net 从url读取一个pdf文件到字节数组

a9wyjsp7  于 2023-06-25  发布在  .NET
关注(0)|答案(4)|浏览(180)

在XML WebResponse中,我得到一个URL标记,它有一个指向PDF文件的链接。URL值的示例为:https://www.member-data.com/files/hb/c8955fc4d6160ec0fd87f4879c6496d3.pdf)。我必须将此PDF转换为字节数组,如何在C#中实现?

a5g8bdjr

a5g8bdjr1#

您可以使用WebClient.DownloadData,它的默认返回值为字节数组。例如

byte[] bytes = myClient.DownloadData("https://www.member-data.com/files/hb/c8955fc4d6160ec0fd87f4879c6496d3.pdf");

此外,这假设您希望实际文件在字节数组中,而不是PDF的内容(文本)。那是另一回事了

xqk2d5yq

xqk2d5yq3#

WebClient已经过时了。使用HttpClient:

string url = "requested/api/url/endpoint"

HttpClient client = new();
client.GetByteArrayAsync(url);

GetByteArrayAsync是awaitable的,所以你的方法应该是async Task:

internal async Task<byte[]?> ReadFile()
{
   string url = "requested/api/url/endpoint"

   using HttpClient client = new();
   return client.GetByteArrayAsync(url);
}

不要忘记释放HttpClient。

nzk0hqpo

nzk0hqpo4#

要将PDF转换为字节数组,请使用System.IO命名空间中的静态方法ReadAllBytes

相关问题