UWP如何访问文件夹中的文件

编程入门 行业动态 更新时间:2024-10-28 10:35:35
本文介绍了UWP如何访问文件夹中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请帮助我,我无法访问由FileOpenPicker选择的文件.

Help me please, I can't get access to file which I choose by FileOpenPicker.

FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.Desktop; openPicker.CommitButtonText = "Открыть"; openPicker.FileTypeFilter.Add(".xlsx"); var file = await openPicker.PickSingleFileAsync(); using (FileStream fs = new FileStream(file.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { }

怎么了?

推荐答案

由于UWP沙箱如何访问文件系统,因此无法直接从StorageFile的路径构造FileStream.相反,您有几种选择,从最简单到最复杂:

Because of how UWP sandboxes access to the filesystem, you can't construct a FileStream directly from a StorageFile's path. Instead, you have a few options, in order from simplest to most complex:

1)如果文件足够小,则可以使用FileIO静态类中的帮助程序一次读取所有内容:

1) If your file is small enough, you can just use the helpers in the FileIO static class to read it all at once:

string text = await FileIO.ReadTextAsync(file); // or ReadLinesAsync or ReadBufferAsync, depending on what you need

2)在StorageFile上使用OpenAsync()方法:

2) Use the OpenAsync() method on StorageFile:

using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read, StorageOpenOptions.AllowReadersAndWriters)) { // your reading code here }

如果需要,可以使用IRandomAccessStream上的AsStream(),AsStreamForRead()和AsStreamForWrite()扩展方法在IRandomAccessStream和.NET Stream之间进行转换,该此处提供的文档.

If you need to, you can convert between IRandomAccessStream and .NET Streams with the AsStream(), AsStreamForRead() and AsStreamForWrite() extension methods on IRandomAccessStream, the docs for which are here.

3)如果要完全控制,则可以使用CreateSafeFileHandle()将SafeFileHandle移至基础文件,如下所示:

3) If you want complete control, you can get a SafeFileHandle to the underlying file using CreateSafeFileHandle(), like so:

SafeFileHandle fileHandle = file.CreateSafeFileHandle(FileAccess.Read, FileShare.ReadWrite);

然后您可以使用此文件句柄创建标准的FileStream:

You can then use this file handle to create a standard FileStream:

using (FileStream fs = new FileStream(fileHandle, FileAccess.Read)) { // Read stuff here }

这是在UWP StorageFile上可靠地使用FileStream的唯一方法,应谨慎使用.官方文档在这样做的含义.

This is the only way to reliably use a FileStream on a UWP StorageFile, and should be used with some caution. The official docs have more details on the implications of doing this.

更多推荐

UWP如何访问文件夹中的文件

本文发布于:2023-10-31 16:51:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1546695.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   夹中   UWP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!