Reputation: 158
I work on an UWP application who manage removable devices. So, I made sure to have this in the manifest.
<Capabilities>
<uap:Capability Name="removableStorage"/>
</Capabilities>
I need to obtain the free and total space of the device. So, I use DriveInfo like this.
DriveInfo z = new DriveInfo(@"E:\");
long x = z.TotalFreeSpace;
This gives the following exception when he tries to obtain the free space and assign it to x :
System.UnauthorizedAccessException : 'Access to the path 'E:\' is denied.'
As you can see, the drive is really a removable drive.
The process I need should occur once the drive as been detected and added. So, this happens in the Added event of a DeviceWatcher
. I see the device is not ready IsReady=false
in the watch window. Maybe I try to access it too soon? The event is "Added", not "Adding" and the UnauthorizedAccessException
is not the one who should occur. I suppose a DeviceNotReadyException
would be more appropriate. So, I conclude the problem is not linked to the fact it is not ready.
Upvotes: 1
Views: 327
Reputation: 39092
Even with the removableStorage
capability declared, you still need to use the UWP APIs to access the files - this means using StorageFolder
APIs. You can use:
var drives = await KnownFolders.RemovableDevices.GetFoldersAsync();
To retrieve all removable drives that you can query. The KnownFolders.RemovableDevices
is actually a virtual folder which contains a subfolder for each removable drive (see docs). To check the drive letter, you can check the Path
of each of the folders.
To retrieve the remaining free space, you can check the properties of the removable storage folder:
var properties = await folder.Properties.RetrievePropertiesAsync(
new string[] { "System.FreeSpace" });
return (UInt64)properties["System.FreeSpace"];
Upvotes: 2