简体   繁体   中英

String of bytes to byte array c#

In my web application, I have a connection to a web service. In my Web Service, it has a method for getting the bytes of a report, based on the path:

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

Now, when I make a request from my web application, the web service gives me a Json object, similar to this:

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

And in my web application I have a method for fetching the Json object, putting the "report" in a string. The web application then has a method for parsing the string of bytes into an array of bytes, which does not work, it throws a 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;
}

I have also tried to do this:

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

Which gave me a .doc file with the exact same string as the Json object had.

Am I parsing something the wrong way from the web service, or is it when I want to convert it to an array of bytes again?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM