【问题标题】:String of bytes to byte array c#字节字符串到字节数组c#
【发布时间】:2013-11-19 18:22:54
【问题描述】:

在我的 Web 应用程序中,我连接到 Web 服务。在我的 Web 服务中,它有一种基于路径获取报告字节的方​​法:

public byte[] GetDocument(string path)
{
   byte[] bytes = System.IO.File.ReadAllBytes(path);
   return bytes;
}

现在,当我从 Web 应用程序发出请求时,Web 服务会为我提供一个 Json 对象,类似于:

{
  "Report":"0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAA
   AAACAAAA3QAAAAAAAAAAEAAA3wAAAAEAAAD+ ... (continues)" 
}

在我的网络应用程序中,我有一个获取 Json 对象的方法,将“报告”放在一个字符串中。 然后,Web 应用程序有一个将字节字符串解析为字节数组的方法,该方法不起作用,它会抛出 FormatException

public byte[] DownloadReport(string id, string fileName)
{
    var fileAsString = _api.DownloadReport(id, fileName);
    byte[] report = fileAsString.Split()
                                .Select(t => byte.Parse(t, NumberStyles.AllowHexSpecifier))
                                .ToArray();
    return report;
}

我也尝试过这样做:

public byte[] DownloadReport(string id, string fileName)
{
   var fileAsString = _api.DownloadReport(id, fileName);
   byte[] report = Encoding.ASCII.GetBytes(fileAsString);
   return report;
}

这给了我一个与 Json 对象完全相同的字符串的 .doc 文件。

我是从 Web 服务中以错误的方式解析某些内容,还是当我想再次将其转换为字节数组时?

【问题讨论】:

  • 请添加你得到的整个异常
  • @Serv,输入的是string was not in a correct format..,然后是一堆路径。但是@Dmytro Rudenko 的回答做到了。
  • 我已经看到,Dmytro 的回答对您有所帮助。

标签: c# json byte


【解决方案1】:
public byte[] DownloadReport(string id, string fileName)
    {
        var fileAsString = _api.DownloadReport(id, fileName);
        byte[] report = Convert.FromBase64String(fileAsString);
        return report;
    }

【讨论】:

  • 感谢上帝/谢谢!我以为我已经尝试过了,但显然我没有。现在就像一个魅力。
猜你喜欢
  • 2021-01-03
  • 1970-01-01
  • 2013-06-19
  • 2011-10-04
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 2015-03-19
  • 2019-05-09
相关资源
最近更新 更多