【问题标题】:Convert StorageFile to string将 StorageFile 转换为字符串
【发布时间】:2018-09-12 15:41:21
【问题描述】:

我们需要将图像文件作为字符串存储在 UWP 应用中。这是计划:

FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".png");
StorageFile file = await picker.PickSingleFileAsync();
byte[] fileBytes = File.ReadAllBytes(file.Path);
string fileString = Convert.ToBase64String(fileBytes);

但线

byte[] fileBytes = File.ReadAllBytes(file.Path);

抛出

System.UnauthorizedAccessException 对路径“C:\MyFolder\ImageFile.png”的访问被拒绝。

对于本练习,每个人都对文件具有完全控制权限。我还将文件移动到包括 U 盘在内的不同位置,但总是遇到相同的异常。我认为这是 UWP 的事情而不是权限的事情?

我们如何在 UWP 应用中将图像文件保存为字符串?

【问题讨论】:

标签: c# uwp


【解决方案1】:

您会遇到异常,因为在 UWP 中您只能通过路径访问文件,位于 App-Package 区域中。

要解决您的问题,您可以使用IBuffer 扩展ToArray

 IBuffer buffer = await FileIO.ReadBufferAsync(file);
 string fileString = Convert.ToBase64String(buffer.ToArray());

【讨论】:

    【解决方案2】:

    您不能直接访问带有字符串路径的文件。在 UWP 中,您应该始终使用 Storage(File, Folder)check this
    访问文件 要获取字节,您可以使用 FileIO 类或 Open Stream with StorageFile。

    【讨论】:

      猜你喜欢
      • 2017-02-06
      • 2019-10-10
      • 2013-05-06
      • 2016-09-22
      • 2019-01-05
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多