How to Stream-ify a StorageFile in UWP

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 😀 .

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:

using System.IO;

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

var stream = await storageFile.OpenStreamForReadAsync();

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

var stream = await storageFile.OpenStreamForWriteAsync();

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

var stream = await storageFolder.OpenStreamForReadAsync("myfile.txt");
//or
var stream = await storageFolder.OpenStreamForWriteAsync("myfile.txt");

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:

var handle = storageFile.CreateSafeFileHandle(options: FileOptions.RandomAccess);
var stream = new FileStream(handle, FileAccess.ReadWrite);

Windows Logo

Buy me a coffeeBuy me a coffee

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.