简体   繁体   中英

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM