Metro获取StorageFile的base64字符串

时间:2013-08-31 23:16:59

标签: c# windows-8 windows-runtime microsoft-metro winrt-xaml

我需要文件选择器选择的文件的base64字符串。

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

返回的字符串总是空的,有什么想法吗?大多数在线示例都是使用不属于W8平台的类

1 个答案:

答案 0 :(得分:10)

试试这个

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