UWP如何访问文件夹中的文件 [英] UWP how to get access to file in folder
问题描述
请帮助我,我无法访问由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 Stream
s 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如何访问文件夹中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!