【问题标题】:C# Binary string to Bytearray without conversionC# 二进制字符串到 Bytearray 无需转换
【发布时间】: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

标签: c# arrays file


【解决方案1】:

按照建议,我们必须更改 API 返回的内容。我们使用 RestSharp 并且不得不使用 Response.RawByte iso。回应。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 2012-10-31
    • 2017-02-23
    • 2014-08-03
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    相关资源
    最近更新 更多