Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Metro getting the base64 string of a StorageFile

I need the base64 string of the file selected by the File Picker.

//file is a StorageFile

FileRandomAccessStream stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.ReadWrite);

using (MemoryStream ms = new MemoryStream())
{
    Stream ss1 = stream.AsStream(); ;
    s1.CopyTo(ms);

}
byteArray = ms.ToArray();
string imageStringSixtyfour = Convert.ToBase64String(byteArray);
if (imageStringSixtyfour != null)
return imageStringSixtyfour;

the returned string is always empty, any ideas? Most examples online are with Classes that are not part of the W8 platform

like image 857
Pedro J. Batista Avatar asked Dec 26 '22 21:12

Pedro J. Batista


1 Answers

Try this

private async Task<string> StorageFileToBase64(StorageFile file)
{
    string Base64String = "";

    if (file != null)
    {
        IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read);
        var reader = new DataReader(fileStream.GetInputStreamAt(0));
        await reader.LoadAsync((uint)fileStream.Size);
        byte[] byteArray = new byte[fileStream.Size];
        reader.ReadBytes(byteArray);
        Base64String = Convert.ToBase64String(byteArray);
    }

    return Base64String;
}
like image 154
Farhan Ghumra Avatar answered Jan 05 '23 20:01

Farhan Ghumra