C# Binary string to Bytearray without conversion - c#

I call an API to get a PDF file. The API returns it as a string with binary data.
Now I need to save it to a file without any conversion of the data.
How can I do this in C#?
I have been trying
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 ();
}
I do get the PDF, but it only has blank pages.
The beginning of the string when i look at it in the Debugger:

As suggested we had to change what the API returned. We use RestSharp and had to use Response.RawByte iso. Response.

Related

Convert docx stream to pdf directly

I need to convert any file coming from web response into .pdf format, I'm currently getting it word docx file format from the URL and saving it into memory stream so i can later insert it in it's designated library.
The problem I'm facing now is that I'm saving my docx files directly into .pdf by putting an extension at the end which obviously ends up not opening the file later, So i'm trying to convert my memory stream into pdf directly .
Here is my piece of code that i tried to convert the the stream to .pdf but it looks like the file isn't getting converted correctly.
private Stream DownloadFromUrl(string url)
{
var webRequest = WebRequest.Create(url);
webRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
webRequest.PreAuthenticate = true;
webRequest.UseDefaultCredentials = true;
//EventLogUtility.LogInformationMessage(DocumentURL);
string message = string.Empty;
using (Stream outputStream = new MemoryStream())
{
using (var response = webRequest.GetResponse())
{
using (var content = response.GetResponseStream())
{
var memory = new MemoryStream();
content.CopyTo(memory);
Document doc = new Document(memory);
doc.Save(memory, SaveFormat.Pdf);
return memory;
}
}
}
}
If the content in the stream is actually in the Microsoft Word file format (and not just plain text), then you need to map the format to the file format for PDF. I know there is a 'Print to PDF' function available in Word, you could try looking into that.

How to save the docx binary data to file in web api C#

I'm fetching a byte[] of a docx file from one API to another and processing it like Application.Documents.Open(array); or File.WriteAllBytes(path, array);
I think the data received is in some UTF-8 format but i have no idea how to convert and process them
Fetching the file from the API using below code.
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
The output(byte[]) is received as string like this.
string result = "PK[][]?......";
Please check the postman screenshot
And trying with below code to save to folder but not working
byte[] res = result .ToArray();
File.WriteAllBytes(#"C:\temp\myfile.docx", res);
also tried this but didn't work,
byte[] mybytearray = Convert.FromBase64String(t);
byte[] barr = Encoding.ASCII.GetBytes(hardcode);
Maybe you should use BinaryReader instead of StreamReader.
See also: https://stackoverflow.com/a/8613300/1438829

Download a PDF from a third party using ASP.NET HttpWebRequest/HttpWebResponse

I want to send a url as query string e.g.
localhost/abc.aspx?url=http:/ /www.site.com/report.pdf
and detect if the above URL returns the PDF file. If it will return PDF then it gets saved automatically otherwise it gives error.
There are some pages that uses Handler to fetch the files so in that case also I want to detect and download the same.
localhost/abc.aspx?url=http:/ /www.site.com/page.aspx?fileId=223344
The above may return a pdf file.
What is best way to capture this?
Thanks
You can download a PDF like this
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = req.GetResponse();
//check the filetype returned
string contentType = response.ContentType;
if(contentType!=null)
{
splitString = contentType.Split(';');
fileType = splitString[0];
}
//see if its PDF
if(fileType!=null && fileType=="application/pdf"){
Stream stream = response.GetResponseStream();
//save it
using(FileStream fileStream = File.Create(fileFullPath)){
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
}
}
response.Close();
The fact that it may come from an .aspx handler doesn't actually matter, it's the mime returned in the server response that is used.
If you are getting a generic mime type, like application/octet-stream then you must use a more heuristical approach.
Assuming you cannot simply use the file extension (eg for .aspx), then you can copy the file to a MemoryStream first (see How to get a MemoryStream from a Stream in .NET?). Once you have a memory stream of the file, you can take a 'cheeky' peek at it (I say cheeky because it's not the correct way to parse a PDF file)
I'm not an expert on PDF format, but I believe reading the first 5 chars with an ASCII reader will yield "%PDF-", so you can identify that with
bool isPDF;
using( StreamReader srAsciiFromStream = new StreamReader(memoryStream,
System.Text.Encoding.ASCII)){
isPDF = srAsciiFromStream.ReadLine().StartsWith("%PDF-");
}
//set the memory stream back to the start so you can save the file
memoryStream.Position = 0;

reading a web api blob into a string that I can send as part of a json object to the server and turn back into a file

i'm trying to turn a wav file into a string I can send to the server as a part of a json object, so that on the server I can turn that string back into a file.
i have tried to use readAsBinaryString and read as text, can't get past error in reading the string into a byte array.
reader.onloadend = saveMedia;
reader.readAsText(Blob);
//reader.readAsBinaryString(Blob); also tried.
then the callback sends an ajax request with an object holding the string in "reader.result" and on the server i tried things like:
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] BinaryData = encoding.GetBytes(stringFromRequest);
the answers to this question below seem to be that this should not be done. but i really want to do it this way because of another tool I am using (breeze js). don't want to use a separate post action with a file data type.
releted:
File API - Blob to JSON
Found a way that works:
var reader = new FileReader();
reader.onloadend = afterRead;
reader.readAsBinaryString(blob);
function afterRead() {
// convert binary string to base64 for a safe transfer to the server.
entity.BinaryProp = window.btoa(reader.result);
}
on the server-side:
string BinaryString = (string)entityInfo.UnmappedValuesMap["BinaryProp"];
byte[] BinaryData = Convert.FromBase64String(BinaryString);
You can use fileReader.readAsDataURL(fileObject), this encode blob to base64, which can safely upload to server by API.
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
let thumbnail = reader.result;
console.log(thumbnail)
//send to API
};
The answer above is great, but there is a simpler way.
var reader = new FileReader();
reader.onloadend = afterRead;
reader.readAsDataURL(blob); // Use this function instead
function afterRead() {
entity.BinaryProp = reader.result; //result is already a base64 string!
}
See documentation here: FileReader.readAsDataURL()

Getting Json Output from Byte Array

I just started a new project on WCF and to be honest I'm very new at this with limited knowledge.
So what I'm trying to do is open a file that is stored in my computer (e.g. word, pdf, etc.) and display the contents in the webpage in JSon format. I converted the file in a byte array and tried to display the Stream. When I did that it asked me to open the file or save it. I don't want that - I just want the contents of the file to be displayed on my local host when i call the method.
Here's what I have:
public string GetRawFile()
{
string file = #"C:\.....\TestFile.pdf";
byte[] rawFile = File.ReadAllBytes(file);
//Stream stream = new MemoryStream(rawFile);
//DataContractJsonSerializer obj = newDataContractJsonSerializer(typeof(string));
//string result = obj.ReadObject(stream).ToString();
//Deserializing
MemoryStream stream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
stream.Write(rawFile, 0, rawFile.Length);
stream.Seek(0, SeekOrigin.Begin);
Object obj = (Object) binForm.Deserialize(stream);
System.Web.Script.Serialization.JavaScriptSerializer xyz = new System.Web.Script.Serialization.JavaScriptSerializer();
string ejson = xyz.Serialize(obj);
WebOperationContext.Current.OutgoingRequest.ContentType = "text/json";
return ejson;
}
I'm trying to return a string and it's not working, but when I return just the stream it's popping up the "openwith" message.
Also should I use the GET or POST on my datacontract. I'm using REST in C#.
I'm assuming that your file actually contains json. If that is the case just do this;
string file = File.ReadAllText("C:\path\to\file.extension");
You're making the problem a lot more complicated than it needs to be. Just read the file and return it's data as a string. I think you want to use GET for the http method. Generally speaking, you all use post if you're adding new content. If for example the users request would cause the application to write some data to a file or data base then you would typically use POST for the http method. If they're just requesting data, you almost always use GET.

Categories