【问题标题】:Call GetDiskFreeSpaceExA from UWP (C#)从 UWP 调用 GetDiskFreeSpaceExA (C#)
【发布时间】:2021-04-21 10:03:19
【问题描述】:

我正在开发一个 UWP 应用程序(C#、Visual Studio 2019),我想了解 C: 的总数、用户免费和可用空间。为此,我想调用 GetDiskFreeSpaceExA(关于 GetDiskFreeSpaceExA:https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdiskfreespaceexa)。

我尝试了以下方法:

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
 [return: MarshalAs(UnmanagedType.Bool)]
 static extern bool GetDiskFreeSpaceExA(string path,
                                        out ulong freeBytesForUser,
                                        out ulong totalNumberOfBytes,
                                        out ulong totalNumberOfFreeBytes);

然后,我调用 GetDiskFreeSpaceExA:

ulong freeUser;
ulong total;
ulong free;
string pathC= @"C:\"; // also tried with "C:\\" and @"C:\\"
bool success =  GetDiskFreeSpaceExA(pathC,
                                    out freeUser,
                                    out total,
                                    out free);

if(success)
{
     // ...
}

成功总是假的。为什么?如何从 UWP 中找出 C: 上的空间?我知道有一些 C# 方法,但我想要 DLL。

谢谢!

【问题讨论】:

  • 仅适用于 Windows。有一些库可以在 MAC 上使用。项目是 x64 还是 x32。
  • 这是一个 Windows 应用程序。很抱歉没有提到这一点!
  • 将 DLL 导入 UWP 应用程序并不简单,因此您的问题可能与您导入 DLL 的方式有关。看看这个答案;它为在 UWP 应用程序中导入 DLL 提供了一些启示:stackoverflow.com/a/33490707/1393899
  • "如果函数失败,则返回值为零 (0)。要获取扩展错误信息,请调用 GetLastError"

标签: c# dll uwp kernel32


【解决方案1】:

您可以在Package.appxmanifest 中添加broadFileSystemAccess 功能。 这是一种受限的能力。可在设置 > 隐私 > 文件系统中配置访问权限。

请参考以下代码。

Package.appxmanifest:

<?xml version="1.0" encoding="utf-8"?>
<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:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap mp rescap">
……
 <Capabilities>
   <rescap:Capability Name="broadFileSystemAccess" />
   <Capability Name="internetClient" />   
 </Capabilities>

后面的代码:

public async void test()
    {

        const String k_freeSpace = "System.FreeSpace";
        const String k_totalSpace = "System.Capacity";

        try
            {
               
                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync("C:\\");
                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 C."));
            }
        
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多