【问题标题】:Error while accessing AvailableFreeSpace/TotalSize in DriveInfo in UWP在 UWP 的 DriveInfo 中访问 AvailableFreeSpace/TotalSize 时出错
【发布时间】:2018-09-10 07:12:46
【问题描述】:

我可以使用 DriveInfo.GetDrives() 方法列出本地磁盘。另外,我使用 Name 属性访问/获取驱动器名称。但我收到错误为“系统。未授权访问异常:'访问路径'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);
}

注意:我在包标签块中放置了以下行 xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" 和

【问题讨论】:

    标签: c# uwp


    【解决方案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>
    

    【讨论】:

    • 不错!您已经通过 StorageFolder 获得了属性!我在驱动器属性上苦苦挣扎,而不是将其路径传递给 StorageFolder。好主意!
    猜你喜欢
    • 2011-11-06
    • 2012-01-13
    • 2011-12-17
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多