I know I can use Win32 APIs for accessing files within my own local data folder (eg, see this answered question) but I need to access files outside of my app (eg, from the Pictures Library) and the libraries I'm trying to use are all based on Win32 file HANDLE
s and / or they rely on using relative filenames.
Since the only way to get at files in the Pictures Library (or to get files / folders returned from a picker) is via StorageFile
objects, how can I re-use my existing code? Do I have to re-write it all to be asynchronous and rely on the WinRT storage APIs?
Starting in the "Anniversary Update" (aka "RS1" or build 10.0.14393) you are able to get a Win32
HANDLE
from aStorageItem
(file or folder) and to create new named files (returning aHANDLE
) from within aStorageFolder
. You do this using the newIStorageFolderHandleAccess
andIStorageItemHandleAccess
APIs.To use one of these new COM interfaces, you simply QI the
StorageFile
orStorageFolder
for the interface. If the interface isn't supported, it means your app is running on a down-level OS (or perhaps the Storage Item isn't actually backed by a real file, but is rather a pseudo-file). You can use these interfaces from C++ (C++/CX or WRL) or from C#.Here's a simple example of using a
FolderPicker
to have the user pick a location on their disk (which returns a brokeredStorageFolder
object) and then using Win32 APIsReadFile
andWriteFile
to read and write a file from that location.As noted above, we have to copy the declarations for the interface into our own code because the real SDK versions are in the wrong API partition. (I would advise against modifying the SDK files to solve the problem). So first up is our own header file, eg
StorageHandleAccess.h
, that copies the declarations from the SDK fileWindowsStorageCOM.h
:Next up is a simple usage of the API. This example takes a
StorageFolder
, a filename, and a creation flag (open or create) and tries to open (or create) the named file, reads (or writes) some text from (to) the file, and writes some output to the Debug console.The code isn't particularly useful in a real-world setting, but illustrates how to use the API. This can be used in a blank C++ XAML project to replace the
MainPage.xaml.cpp
file (you should only need to update the namespace):