使用C#在WinRT中获取可用磁盘空间

时间:2013-03-14 16:45:43

标签: c# windows-8 microsoft-metro windows-store-apps

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool GetDiskFreeSpaceEx(
            string lpDirectoryName,
            out ulong lpFreeBytesAvaliable,
            out ulong lpTotalNumberOfBytes,
            out ulong lpTotalNumberOfFreeBytes);

        // Returns free disk space from directory.
        public static ulong GetFreeDiskSpace(string directory)
        {
            ulong a, b, c;

            if (GetDiskFreeSpaceEx(directory, out a, out b, out c))
            {
                Debug.WriteLine(a);
            }


            return a;
        }

我正在开发一个Windows应用商店应用。我打电话时为什么变量包含0:

GetFreeDiskSpace("C:\\");

不执行Debug.WriteLine(a)行。

2 个答案:

答案 0 :(得分:1)

研究其他内容我最终找到答案:“在Windows 8 Metro Apps中,您不能访问文件夹或在KnownFolders之外进行驱动。”

MSDN

答案 1 :(得分:0)

您正在写错误的驱动器。它必须是这样的:

GetFreeDiskSpace("C:");

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool GetDiskFreeSpaceEx(
    string lpDirectoryName,
    out ulong lpFreeBytesAvailable,
    out ulong lpTotalNumberOfBytes,
    out ulong lpTotalNumberOfFreeBytes);

也在另一页上找到了这个。在WinRT上有所不同

Unable to get free disk space from Metro-style app

static void TestDiskSpace()
{
    IStorageFolder appFolder = ApplicationData.Current.LocalFolder;
    ulong a, b, c;
    if(GetDiskFreeSpaceEx(appFolder.Path, out a, out b, out c))
        Debug.WriteLine(string.Format("{0} bytes free", a));
}