Aleff
Aleff

Reputation: 257

Get free disk space in WinRT using C#

        [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;
        }

I'm developing a Windows Store App. Why a variable contains 0 when I call:

GetFreeDiskSpace("C:\\");

?

The line with Debug.WriteLine(a) isn't executed.

Upvotes: 3

Views: 1400

Answers (2)

Aleff
Aleff

Reputation: 257

Researching something else I ended up finding the answer: "In Windows 8 Metro Apps you are not allowed to access folders or drive outside of the KnownFolders."

MSDN

Upvotes: 1

Kirk Backus
Kirk Backus

Reputation: 4866

You are writing the drive wrong. It needs to be this:

GetFreeDiskSpace("C:");

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

Also found this on another page. It is different on 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));
}

Upvotes: 0

Related Questions