【发布时间】:2020-03-10 06:23:14
【问题描述】:
我调用 API 来获取 PDF 文件。 API 将其作为带有二进制数据的字符串返回。 现在我需要将它保存到一个文件中,而不需要对数据进行任何转换。 如何在 C# 中做到这一点?
我一直在努力
string file = await service.GetDocumentsAsync(document.FileId); // Gets the filedata
byte[] byteArray = file.Select (c => (byte)c).ToArray ();
using (var stream = new FileStream($"c:\\temp\\{document.Id}.pdf", FileMode.Create))
{
stream.Write (byteArray,0,file.Length);
stream.Close ();
}
我确实得到了 PDF,但它只有空白页。
当我在调试器中查看字符串时的开头:
【问题讨论】:
-
“带有二进制数据的字符串” 什么意思? Base64 编码?
-
"带有二进制数据的字符串" 比如 "0100101100" => How To Write A String Of Binary To File C# ;如果它看起来像 "aGVsbG8gd29ybGQK" => Base64 encoded string to file
-
File.WriteAllText("C:\\...", file);有什么问题? -
@Longoon12000 因为 PDF 文件通常包含数据,如果将其视为字符串(文本)而不是将其视为字节,则会损坏这些数据。
-
service.GetDocumentsAsync需要提供byte[],而不是string。