1

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.

Reza M.A
  • 1,197
  • 1
  • 16
  • 33
  • 1
    It can also be written in python or java. There is no limitation for language. – Reza M.A Jul 15 '13 at 21:11
  • possible duplicate of [How do I convert from 8 bit byte to 7 bit byte (Base 256 to Base 128)](http://stackoverflow.com/questions/976975/how-do-i-convert-from-8-bit-byte-to-7-bit-byte-base-256-to-base-128) – I4V Jul 15 '13 at 21:16
  • no,not at all, I want to encode a file to base128 not base256 to base 128 !! – Reza M.A Jul 15 '13 at 21:19
  • 1
    Reza read Jon Skeet's answer again (`... There is no 7-bit alphabet with the same properties ......`) – I4V Jul 15 '13 at 21:21

1 Answers1

1

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);
  }
}
Joshua
  • 8,112
  • 3
  • 35
  • 40