Convert 64base byte array to PDF and show in webBroswer compont - c#

This is what i would like to do:
Get a 64base byte array from database (which is actually in pdf format). This works.
Then i would like to show the pdf in a webbrowser component.
I first started with saving the pdf to a file.pdf and then open it:
byte[] bitjes = isc.GetFileById(fileid); // Getting the bytes
FileStream stream = new FileStream(#"C:\NexusPDF\" + filename, FileMode.CreateNew);
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(bitjes, 0, bitjes.Length);
writer.Close();
webBrowser.Navigate(#"C:\NexusPDF\" + filename);
But that gave me all sorts of problems involving read/write acces. So i figured i have to use the memorystream class to solve this problem.
byte[] bitjes = isc.GetFileById(fileid);
MemoryStream memstream = new MemoryStream(bitjes);
BinaryWriter writer = new BinaryWriter(memstream);
writer.Write(bitjes, 0, bitjes.Length);
writer.Close();
But here's where i'm stuck! I can't just show this in a webBrowser component can i?
Do i have to use the binaryreader before i can show the pdf?
Am i approaching this problem the right way, or are there better alternatives?
Main thing is that i don't want to save the file on disk.
Any help will be appreciated.

You may be able to use the data URL scheme. This URL scheme specifies the content inline.
webBrowser.Navigate("data:application/pdf;base64," + X);
Where X is the base 64 string.
No need to convert the base 64 PDF string into a byte array!
See http://www.ietf.org/rfc/rfc2397.txt for more details.

Related

Issues with saving XML file (C#)

I'm trying to make a config file from an XML file, but I can't figure out how to save the file after I add to it. I can read from the file fine, so I know it's not an issue with where it's located, but I still don't know how to save it.
I've looked around for about 2 hours and can't figure out the problem. I'm know my way around c# but am completely new to XML.
public async Task CreateReaction(string name, DiscordMessage message, DiscordEmoji emoji, DiscordRole role)
{
string path = #"E:\Visual Studio\repos\JustHangoutBot\bin\Debug\netcoreapp1.1\configs\reactions.xml";
XDocument doc = XDocument.Load(path);
await message.CreateReactionAsync(emoji);
XElement root = new XElement(name);
root.Add(new XElement("MessageID", message.Id));
root.Add(new XElement("ReactionID", emoji.Id));
root.Add(new XElement("RoleID", role.Id));
doc.Element("Reactions").Add(root);
byte[] byteArray = Encoding.UTF8.GetBytes(path);
MemoryStream stream = new MemoryStream(byteArray);
doc.Save(stream);
}
I think the problem is somewhere in the last three lines. I've seen tutorials of people saving the file by just using doc.Save("reactions.xml") for example, but I get the error of not being able to convert from string to Stream.
Any help would be appreciated. Thank you in advance!
This will do it:
using (var fileStream = System.IO.File.OpenWrite("path to the file you want to write"))
{
doc.Save(fileStream);
}
When you do this:
byte[] byteArray = Encoding.UTF8.GetBytes(path);
MemoryStream stream = new MemoryStream(byteArray);
doc.Save(stream);
What's happening is
You're opening the file at path and reading it into a byte array.
You're creating a MemoryStream that has those bytes as its content
You're saving that document to the MemoryStream.
Under the hood a MemoryStream is just an array of bytes in memory. So it's writing the file to memory, not to a file.
File.OpenWrite(path) opens a FileStream with the specified path. If the file doesn't exist it creates it. If the file does exist it will overwrite it.
So when you call doc.Save(fileStream) you're writing to the file.

String to zip file

I use a webservice that returns a zip file, as a string, and not bytes as I expected. I tried to write it to the disk, but when I open it, it tells me that it is corrupt. What am I doing wrong?
string cCsv = oResponse.fileCSV;//this is the result from webservice
MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(cCsv));
using (FileStream file = new FileStream("test.zip", FileMode.Create, FileAccess.Write))
{
ms.WriteTo(file);
}
ms.Close();
I'm not sure what kind of encoding the string is in, but assuming UTF-8, the following should work. UTF-16 would be another guess.
string cCsv = oResponse.fileCSV;
using (BinaryWriter bw = new BinaryWriter(File.Create("test.zip")))
{
bw.Write(System.Text.Encoding.UTF8.GetBytes(cCsv));
}
It'd be informative to look at the characters and the raw string itself being returned.
Edit
Per Frank's answer, the correct encoding is base64, which of course makes sense because it's binary data stored as a string.
Also, per Frank's answer, if the only action is to directly write a single byte array, then File.WriteAllBytes is more compact.
Ok, i solve the problem:
File.WriteAllBytes("testbase64.zip", Convert.FromBase64String(cCsv));

Download from byte array from CRM

In Microsoft CRM we have an attachment that should be fetched and downloaded. So I have a byte array that represents the fetched file:
byte[] fileContent = Convert.FromBase64String(query.DocumentBody);
If I use this code, of course it can be downloaded but the file path should be hardcoded (like C:/<folder name>/) and I don't want it like that.
using (FileStream fileStream = new FileStream(path + query.FileName, FileMode.OpenOrCreate))
{
byte[] fileContent = Convert.FromBase64String(query.DocumentBody);
fileStream.Write(fileContent, 0, fileContent.Length);
//Response.OutputStream.WriteByte(fileContent);
}
How can I download the file from a byte array? I've tried searching for ways but it all needs a file path, and I can't provide that file path since the object is a byte array.
I'm not sure what exactly is your problem, but following should write byte array to output stream. You may need "content-disposition" header for file name and "content-type" to let browser offer "download" instead of trying to open directly:
Response.OutputStream..Write(fileContent , 0, fileContent .Length);

Byte array to a file

I have a byte array for a file, is there a way to take that and save it has a file to a remote file server?
File.WriteAllBytes(#"\\server\public_share\MyFile.txt", byteArray);
Writing your data to file is the simple part and #aaron has shown you how...
i.e. File.WriteAllBytes(....etc
But something to be aware of, if you're transferring binary data over the wire and if your data contains bytes that could be interpreted as control characters then your data transfer will be problematic.
What you may need to do is encode your data first so that you can transfer it safely, typically you would use something like Base64 encoding.
You can use the Convert helper class to do that...
Convert.ToBase64String("file contents");
If you are doing this in the codebehind then you will need to use the FileStream and BinaryWriter objects.
Something like this;
FileStream filestream = new FileStream("myfile.txt", FileMode.Open);
BinaryReader br = new BinaryReader(filestream);
String msg = br.ReadString();
br.Close();
filestream.Close();
FileStream networkStream = new FileStream(#"\\server\share\file.txt", FileMode.Create);
BinaryWriter bw = new BinaryWriter(filestream);
bw.Write(msg);
bw.Close();
networkStream.Close();
If you're passing it through Javascript maybe using a HTML browse button then you'll need to do the same sort of thing but you will get the file stream from the post form request.
You may have an issue writing to the network location, if you're using IIS then you could set up a virtual directory and set the credentials in IIS. The alternative is that you will need to do impersonation to write the file to the network server.
Mike

How to convert byte array to image file?

I have browsed and uploaded a png/jpg file in my MVC web app.
I have stored this file as byte[] in my database.
Now I want to read and convert the byte[] to original file.
How can i achieve this?
Create a MemoryStream passing the array in the constructor.
Read the image from the stream using Image.FromStream.
Call theImg.Save("theimage.jpg", ImageFormat.Jpeg).
Remember to reference System.Drawing.Imaging and use a using block for the stream.
Create a memory stream from the byte[] array in your database and then use Image.FromStream.
byte[] image = GetImageFromDatabase();
MemoryStream ms = new MemoryStream(image);
Image i = Image.FromStream(ms);
May you have trouble with the mentioned solutions on DotNet Core 3.0 or higher
so my solution is:
using(var ms = new MemoryStream(yourByteArray)) {
using(var fs = new FileStream("savePath", FileMode.Create)) {
ms.WriteTo(fs);
}
}
Or just use this:
System.IO.File.WriteAllBytes(string path, byte[] bytes)
File.WriteAllBytes(String, Byte[]) Method (System.IO) | Microsoft Docs

Categories

Resources