crystyxn
crystyxn

Reputation: 1601

String to byte array to file for POST request

I am retrieving a PDF file from SharePoint that comes in as text (not plain, encoded). I want to turn this into an actual PDF file to then upload it to another URL via a POST request.

 var client2 = new RestClient("https://preactdk.redacted.com/sites/mysite/_api/web/GetFileByServerRelativeUrl('/sites/mysite/Shared%20Documents/testfolder/test.pdf')/$value");
 client2.Timeout = -1;
 var request2 = new RestRequest(Method.GET);
 request2.AddHeader("Authorization", $"Bearer {tokenData.access_token}");
 request2.AddHeader("Accept", "application/json;odata=verbose");
 IRestResponse response2 = client2.Execute(request2);
 
 string content = response2.Content;
 byte[] bytes = Encoding.ASCII.GetBytes(content);
 var myfile = System.IO.File.WriteAllBytes("test.pdf", bytes);
                  
        
 var clientUpload = new RestClient("https://mysite.azurewebsites.net/api/Upload");
 RestRequest requestUpload = new RestRequest(Method.POST);
 //requestUpload.AddHeader("Content-Type", "multipart/form-data");
 requestUpload.AddFile("File", bytes, "test.pdf");
 var responseUpload = clientUpload.Post(requestUpload);

I've tried to convert it to a byte array but without much success. How do I create the PDF in memory stream or file stream and pass it to the POST request function ? This function takes a pdf file in its body via POST.

Upvotes: 0

Views: 2050

Answers (1)

crystyxn
crystyxn

Reputation: 1601

What I needed was to use

byte[] bytes = response2.RawBytes;

directly. It worked smoothly and the PDF displays correctly.

Upvotes: 1

Related Questions