C#: Encoding and decoding Base 64 strings

Sometimes you would have to make sure that data in images, PDF files or documents of other file types remain intact without modification while being transported over mediums that are designed to work with textual data. In these cases, you would have had to deal with Base 64 strings while uploading/downloading images, PDF files or documents in other formats. Base 64 encoded data is used mostly while transferring data over email, json, html or for saving complex data in XML formats.

Encoding images picked using FilePicker to Base 64 string:

FileOpenPicker openPicker = new FileOpenPicker();
// Set the start location and view mode for the picker
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
// Adding file types that may be allowed in the attachment
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
// Open a stream for the selected file.
IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
// Set the image source to the selected bitmap.
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(fileStream);
attachmentImage.Source = bitmapImage;
// Create a byte array for the image
Byte[] picAttachment = new Byte[0];
var reader = new DataReader(fileStream.GetInputStreamAt(0));
picAttachment = new Byte[fileStream.Size];
await reader.LoadAsync((uint)fileStream.Size);
reader.ReadBytes(picAttachment);
// Convert the byte array to Base 64 string
string base64String = Convert.ToBase64String(picAttachment);
}

Decoding Base 64 string to an Image:

BitmapImage bmp = new BitmapImage();
// Convert the Base 64 string to a byte array
byte[] imageBytes = Convert.FromBase64String(base64String);
using (MemoryStream ms = new MemoryStream(imageBytes))
{
// create IRandomAccessStream
var stream = ms.AsRandomAccessStream();
stream.Seek(0);
// create bitmap and assign
await bmp.SetSourceAsync(stream);
image = bmp; // where image is an Image control in XAML
}

Decoding Base 64 string to PDF document:

// Open a stream for the selected file
var byteArray = Convert.FromBase64String(base64string);
// Create a PDF file in the local folder
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Bill.pdf", CreationCollisionOption.ReplaceExisting);
var buffer = Windows.Security.Cryptography.CryptographicBuffer.CreateFromByteArray(byteArray);
// Write to the file using the buffer
await FileIO.WriteBufferAsync(file, buffer);
// Launch the PDF file using file launcher
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
options.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.UseHalf;
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);