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) 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) Use the OpenAsync()
method on StorageFile:
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read, StorageOpenOptions.AllowReadersAndWriters))
{
// your reading code here
}
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) 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);
You can then use this file handle to create a standard FileStream
:
using (FileStream fs = new FileStream(fileHandle, FileAccess.Read))
{
// Read stuff here
}
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.