C#中字节串转换为字节数组

3

在我的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对象,并将“报告”放入一个字符串中。 然后,该网络应用程序具有将字节字符串解析为字节数组的方法,但此方法不起作用,会引发“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;
}

我使用了一个web服务,得到了一个Json对象,然后我将其转换为字节数组,并生成了一个与Json对象完全相同的.doc文件。

但是我不确定是在解析web服务时出了问题,还是在想要再次将其转换为字节数组时出了问题?


请添加您所获得的完整异常信息。 - Marco
1
@Serv,它提示“字符串格式不正确..”,然后是一堆路径。但是@Dmytro Rudenko的答案解决了这个问题。 - Moelbeck
1
我已经看到Dmytro的回答对你有所帮助。 - Marco
1个回答

8
public byte[] DownloadReport(string id, string fileName)
    {
        var fileAsString = _api.DownloadReport(id, fileName);
        byte[] report = Convert.FromBase64String(fileAsString);
        return report;
    }

1
谢天谢地/谢谢!我以为我已经尝试过这个了,但显然我没有。现在完美运行。 - Moelbeck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接