How to Stream-ify a StorageFile in UWP

WinUI

4 years ago

Access to the file system in UWP is limited for security. Even with the broadFileSystemAccess capability, non-Windows.Storage APIs still can't access files outside of the app's folder by file path. Luckily, most methods offer an overload, which expects a System.IO.Stream argument, which works around this problem swiftly. But how to turn the StorageFile instance into a Stream? That's something I keep forgetting all the time, so hopefully, this article will help me remember this once for all :-D . StorageFile does not provide such conversion methods directly. Instead, they are defined as extension methods in the WindowsRuntimeStorageExtensions type located in the System.IO namespace. So first add the using statement to the top of your C# file:

And now we call the OpenStreamForReadAsync method on our StorageFile to get a read-only Stream:

Or call OpenStreamForWriteAsync method to get a write-able Stream:

There are even overloads that allow us to get a Stream for a file within a specific folder, using a StorageFolder instance:

Finally, if we want to go one level down, we can use the CreateSafeFileHandle method, which returns a Microsoft.Win32.SafeHandles.SafeFileHandle. This handle can be, for example, used with the FileStream API:

Windows Logo