1

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.

enter image description here

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.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
sbeaudoin
  • 158
  • 2
  • 11
  • Check out https://daniel-krzyczkowski.github.io/UWP-External-file-system-access-and-environment-variables/ this may help resolve your issues – Xavier Dec 29 '20 at 22:35
  • Yes, I have seen the broad filesystem access capability, but I will need to justify this choice to Microsoft, something I would not be able to do. So, thanks anyway. – sbeaudoin Dec 30 '20 at 23:05

1 Answers1

2

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"];
Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
  • 1
    Thank you for the information, but the GetFolders is irrelevant as I want to be notified by the watcher. Concerning the properties, they are so confusing to find which are supported by which device. I found out DriveInfo and wanted to use it. I used your method as a workaround and notified the framework team on github. As your solution is near what I did, you are the winner of a point! – sbeaudoin Dec 30 '20 at 23:04