Conversion from binary to byte[] in c# - c#

I have an attachment of a MIME file which is encoded in binary format.
That binary data from the file is stored in a string variable in my application. My task is to convert that string to byte[] so that i can pass this to a stream object to upload it in the Azure blob storage. I am using the below code. Code does not break but once the it gets uploaded to Azure blob and I try to download it shows file is corrupt.
attachmentContents is the string object which contains the binary data.
//# byteAttachmentData is the byte[]
byteAttachmentData = UTF8Encoding.UTF8.GetBytes(attachmentContents)
Sample of binary data(Not pasting the entire content)
PK ! ̘Շʁ ͇ [Content_Types].xml ( ԕ̪ðE󅾃ѶيڨƄɢХh򁊴ύ͇Ӥ񷝇Ω%ʃo򌽷ّͤdċh>֤l،XFZUمʾfo񣋂
Ąi
ŬƷ7ęׁɈmB˲D󄹐9h쁐%ԞŗࠠNɯѠ~?

Related

Convert Base64 String to an Image File and Save it to File System?

I am trying to make a .Net 6 console application that would take in a base64string and then save it to the file system as an actual image file
Example
I have this image
https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_960_720.png
I would have this image already as a base64 string.
Now I want to save to my file system as "cat-1285634_960_720.png"
I just can't figure out how to do it. All the examples I see say to use Image.Save() but I can't find that in .Net6 and looks like it is removed.
First convert the base64 string to a byte array and then use File.WriteAllBytes(...) to save it:
byte[] imageByteArray = Convert.FromBase64String(base64String);
File.WriteAllBytes("image.png", imageByteArray);

Azure Storage Blobs - Upload base64 as Text

I have an API server method that accept getting files as BASE64. Getting request like this:
{
file: "-BASE 64 HERE-"
}
I want that my server will get this file and store it on Azure Storage. So, I running this code:
var blob = container.GetBlockBlobReference("file.zip");
var buffer = Convert.FromBase64String(Model.File);
await blob.UploadFromByteArrayAsync(buffer, 0, buffer.Length);
It's working, but inefficient.
Why? Because the same bytes have two instances in my main memory: as byte array + as stream.
I wounder if it possible to upload the BASE64 as text, and letting the server understand that this is BASE64 - which will be treated like a file.
In that way I will upload the text directly without convert it to stream.
Is this possible?
May be linked to this thread
Thanks.
Can't you just use UploadFromStreamAsync?

Decompressing a Zip file from a string

I'm fetching an object from couchbase where one of the fields has a file. The file is zipped and then encoded in base64.
How would I be able to take this string and decompress it back to the original file?
Then, if I'm using ASP.MVC 4 - How would I send it back to the browser as a downloadable file?
The original file is being created on a Linux system and decoded on a Windows system (C#).
You should use Convert.FromBase64String to get the bytes, then decompress, and then use Controller.File to have the client download the file. To decompress, you need to open the zip file using some sort of ZIP library. .NET 4.5's built-in ZipArchive class should work. Or you could use another library, both SharpZipLib and DotNetZip support reading from streams.
public ActionResult MyAction()
{
string base64String = // get from Linux system
byte[] zipBytes = Convert.FromBase64String(base64String);
using (var zipStream = new MemoryStream(zipBytes))
using (var zipArchive = new ZipArchive(zipStream))
{
var entry = zipArchive.Entries.Single();
string mimeType = MimeMapping.GetMimeMapping(entry.Name);
using (var decompressedStream = entry.Open())
return File(decompressedStream, mimeType);
}
}
You'll also need the MIME type of the file, you can use MimeMapping.GetMimeMapping to help you get that for most common types.
I've used SharpZipLib successfully for this type of task in the past.
For an example that's very close to what you need to do have a look here.
Basically, the steps should be something like this:
you get the compressed input as a string from the database
create a MemoryStream and write the string to it
seek back to the beginning of the memory stream
use the MemoryStream as an input to the SharpZipLib ZipFile class
follow the example provided above to unpack the contents of the ZipFile
Update
If the string contains only the zipped contents of the file (not a full Zip archive) then you can simply use the GZipStream class in .NET to unzip the contents. You can find a sample here. But the initial steps are the same as above (get string from db, write to memory stream, feed memory stream as input to the GZipStream to decompress).

byte array to pdf

I am trying to convert content of a file stored in a sql column to a pdf.
I use the following piece of code:
byte[] bytes;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, fileContent);
bytes = ms.ToArray();
System.IO.File.WriteAllBytes("hello.pdf", bytes);
The pdf generated is corrupt in the sense that when I open the pdf in notepad++, I see some junk header (which is same irrespective of the fileContent). The junk header is NUL SOH NUL NUL NUL ....
You shouldn't be using the BinaryFormatter for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.
If it's stored in the database, hopefully, as a varbinary - then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.
With any luck - I'm hoping that fileContent here is the byte array? In which case you can just do
System.IO.File.WriteAllBytes("hello.pdf", fileContent);
Usually this happens if something is wrong with the byte array.
File.WriteAllBytes("filename.PDF", Byte[]);
This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
Asynchronous implementation of this is also available.
public static System.Threading.Tasks.Task WriteAllBytesAsync
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);

PDF content inside XML response file

I receive XML file that includes PDF content:
<pdf>
<pdfContent>JVBERi0xLjQKJaqrrK0KNCAwIG9iago8PCAvV.......
How can I save the content into PDF file?
I'm using C# 4.0
That string value is the PDF in base64. If you convert the base64 to a byte array you can just write that byte array to disk.
Convert.FromBase64String
var buffer = Convert.FromBase64String(xmlStringValue);
File.WriteAllBytes(yourFileName, buffer);
It looks like the pdf content is encoded in base64. You will have to decode it and save it to a file.
Edit: indeed, when I use base64 to encode a pdf file, the first few characters are JVBERi0x...
It seems encoded with Base64, But not sure. if it is, you can take that long string and convert with the function Convert.FromBase64. You will obtain a byte[] that you can save as the actual pdf.

Categories