在UWP中访问DriveInfo中的AvailableFreeSpace / TotalSize时出错

时间:2018-09-10 07:12:47

标签: c# uwp

我能够使用DriveInfo.GetDrives()方法列出本地磁盘。另外,我使用“名称”属性访问/获取驱动器名称。但是我收到错误消息“系统。UnauthorizedAccess异常:​​'对路径'X:\'的访问被拒绝。”在访问任何属性(如AvailableFreeSpace)时。下面的代码。

DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
   Debug.WriteLine("Drive: " + d.Name); //This line executes w/o error!
   Debug.WriteLine("Drive: " + d.AvailableFreeSpace);
   Debug.WriteLine("Drive: " + d.TotalSize);
}

注意:我在包标记块和在“功能”标签块内,位于我项目的Package.appxmanifest文件中。

1 个答案:

答案 0 :(得分:1)

使用以下代码,我可以为某些驱动器获取总的可用磁盘空间:

        const String k_freeSpace = "System.FreeSpace";
        const String k_totalSpace = "System.Capacity";
        DriveInfo[] allDrives = DriveInfo.GetDrives();
        foreach (DriveInfo d in allDrives)
        {
            try
            {
                Debug.WriteLine("Drive: " + d.Name);
                Debug.WriteLine("RootDir: " + d.RootDirectory.FullName);

                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(d.RootDirectory.FullName);
                var props = await folder.Properties.RetrievePropertiesAsync(new string[] { k_freeSpace, k_totalSpace });
                Debug.WriteLine("FreeSpace: " + (UInt64)props[k_freeSpace]);
                Debug.WriteLine("Capacity:  " + (UInt64)props[k_totalSpace]);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(String.Format("Couldn't get info for drive {0}.  Does it have media in it?", d.Name));
            }
        }

我的“最低版本”和“目标版本”均以Windows 10版本1803(10.0:内部版本17134)为目标。

以下是我Package.appxmanifest中的一些摘录

<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" 
         xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" 
         xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" 
        xmlns:iot="http://schemas.microsoft.com/appx/manifest/iot/windows10" 
        xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" 
        IgnorableNamespaces="uap mp iot rescap">

...

<Capabilities>
    <Capability Name="internetClient" />
    <rescap:Capability Name="broadFileSystemAccess" />
  </Capabilities>
</Package>