Encode a FileStream to base64 with c#
You can also encode bytes to Base64. How to get this from a stream see here: How to convert an Stream into a byte[] in C#?
Or I think it should be also possible to use the .ToString() method and encode this.
Converting file into Base64String and back again
If you want for some reason to convert your file to base-64 string. Like if you want to pass it via internet, etc... you can do this
Byte[] bytes = File.ReadAllBytes("path");
String file = Convert.ToBase64String(bytes);
And correspondingly, read back to file:
Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);
How to convert base64 value from a database to a stream with C#
You'll want to do something like this, once you've gotten the string from the database:
var bytes = Convert.FromBase64String(base64encodedstring);
var contents = new StreamContent(new MemoryStream(bytes));
// Whatever else needs to be done here.
Is there a Base64Stream for .NET?
If you want a stream that converts to Base64, you can put a ToBase64Transform
into a CryptoStream
:
new CryptoStream(stream, new ToBase64Transform(), CryptoStreamMode.Write)
If you just want to convert a single byte array to Base64, you can simply call Convert.ToBase64String(bytes)
.
In both cases, you can replace the word To
with From
.
Convert a VERY LARGE binary file into a Base64String incrementally
Based on the code shown in the blog from Wiktor Zychla the following code works. This same solution is indicated in the remarks section of Convert.ToBase64String as pointed out by Ivan Stoev
// using System.Security.Cryptography
private void ConvertLargeFile()
{
//encode
var filein= @"C:\Users\test\Desktop\my.zip";
var fileout = @"C:\Users\test\Desktop\Base64Zip";
using (FileStream fs = File.Open(fileout, FileMode.Create))
using (var cs=new CryptoStream(fs, new ToBase64Transform(),
CryptoStreamMode.Write))
using(var fi =File.Open(filein, FileMode.Open))
{
fi.CopyTo(cs);
}
// the zip file is now stored in base64zip
// and decode
using (FileStream f64 = File.Open(fileout, FileMode.Open) )
using (var cs=new CryptoStream(f64, new FromBase64Transform(),
CryptoStreamMode.Read ) )
using(var fo =File.Open(filein +".orig", FileMode.Create))
{
cs.CopyTo(fo);
}
// the original file is in my.zip.orig
// use the commandlinetool
// fc my.zip my.zip.orig
// to verify that the start file and the encoded and decoded file
// are the same
}
The code uses standard classes found in System.Security.Cryptography namespace and uses a CryptoStream
and the FromBase64Transform
and its counterpart ToBase64Transform
Convert an image (selected by path) to base64 string
Get the byte array (byte[]
) representation of the image, then use Convert.ToBase64String()
, st. like this:
byte[] imageArray = System.IO.File.ReadAllBytes(@"image file path");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
To convert a base64 image back to a System.Drawing.Image
:
var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64String)));
Encode zip file to Base64
Don't try to do the whole thing in one chunk.
Loop through bytes from your FileStream. Grab multiples of three bytes and encode those. Be sure to use a StringBuilder to build your output.
That will greatly decrease memory usage.
MemoryStream to String, and back to MemoryStream without adding any bytes (encodings, etc.)
Let's say, that your MemoryStream contains the following input data: [0x01, 0x02, 0x03, 0x04]
When you read it with streamreader, the binary representation of your string will be: [0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04], because strings use two byte representation for a character. What you do afterwards is that you allocate 8 bytes for your "bytes" variable instead of 4, and fill it with the second (modified) data. You can use Convert.ToBase64String() to get a string representation, also you can use FromBase64String() to parse it back. Something like this:
var testData = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
var inputStream = new MemoryStream(testData);
var inputAsString = Convert.ToBase64String(inputStream.ToArray());
Console.WriteLine(inputAsString);
var outputStream = new MemoryStream(Convert.FromBase64String(inputAsString));
var result = BitConverter.ToString(outputStream.ToArray());
Console.WriteLine(result);
Related Topics
How to Save/Download Pdf Embedded in Web Page Without a Pdf Filename
Declare Properties to Ignore in Entities Interface (Ef Core)
C# Replace Item in List<String> "/"
Linq Multiple Group by in a List<T> Then Convert to List<T>
How to Submit Disabled Input in ASP.NET MVC
Restsharp Post Request - Body With X-Www-Form-Urlencoded Values
How to Get Only Date from a Datetime Value in Razor Page
How to Refresh or Show Immediately in Datagridview After Inserting
Count() a Specfic Attribute Within a List C#
How to Hide a Property in Webapi
How to Reference Assemblies Using Visual Studio Code
How to Secure the Asp.Net_Sessionid Cookie
Lambda Where Id Does Not Exist in Another List
How to Get the Current Project Directory from C# Code When Creating a Custom Msbuild Task
How to Perform Join Between Multiple Tables in Linq Lambda
How to Test If a Instance of a Class Is a Specific Generic Type
What Regular Expression Would I Use to Remove Everything After the Second Backslash