How to encode a file to base64 in C# and how to retrieve it?
for example encode a zip file to base64 and retrieve it again.
How to encode a file to base64 in C# and how to retrieve it?
for example encode a zip file to base64 and retrieve it again.
Your best bet is to use the ToBase64Transform and FromBase64Transform crypto interfaces.
The basic gist behind this code sample is that you use the From/ToBase64Transform transform class with the standard crypto stream to handle the heavy work of converting the incoming data to or from base64. In the ConvertToBase64
method, you'll notice that it wraps the destination file stream with the "ToBase64" crypto stream and we then copy the contents from the source stream to the base64 crypto stream. It's the same when decoding, you just apply it slightly backwards. We wrap the source stream in a "FromBase64" to decode the data as it comes in and we use it to copy it to the destination stream.
A very rough (and untested example) would be something like:
using System;
using System.IO;
using System.Security.Cryptography;
void ConvertToBase64(string sourceFileName, string destFileName) {
FileStream source = new FileStream(sourceFileName, FileMode.Open,
FileAccess.Read, FileShare.Read);
FileStream dest = new FileStream(destFileName, FileMode.Create,
FileAccess.Write, FileShare.None);
ICryptoTransform base64 = new ToBase64Transform();
CryptoStream cryptoStream = new CryptoStream(dest, base64, CryptoMode.Write);
using (source) using (dest) using (base64) using (cryptoStream) {
source.CopyTo(cryptoStream);
cryptoStream.FlushFinalBlock();
}
}
void ConvertFromBase64(string sourceFileName, string destFileName) {
FileStream source = new FileStream(sourceFileName, FileMode.Open,
FileAccess.Read, FileShare.Read);
ICryptoTransform base64 = new FromBase64Transform();
CryptoStream cryptoStream = new CryptoStream(source, base64, CryptoMode.Read);
FileStream dest = new FileStream(destFileName, FileMode.Create,
FileAccess.Write, FileShare.None);
using (source) using (base64) using (cryptoStream) using (dest) {
cryptoStream.CopyTo(dest);
}
}