Failed to get free disk space from Metro-style app.

I am writing a Metro style application and want to determine the available storage capacity on which the user’s music library is located. I want to disable some functions of the application while there is no or little disk space. I use P / Invoke to call GetDiskFreeSpaceExW and get errors and invalid bytes.

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

[DllImport("kernel32.dll", SetLastError = true)]
static extern int GetLastError();

async static void TestDiskSpace()
{
   IStorageFolder musicFolder = KnownFolders.MusicLibrary;
   IStorageFolder testFolder = await musicFolder.CreateFolderAsync("test", CreationCollisionOption.OpenIfExists);
   IStorageFolder appFolder = ApplicationData.Current.LocalFolder; 
   ulong a, b, c;
   string[] paths = new[]
   {
      null,
      "."
      "C:",
      "C:\\",
      "C:\\Users\\Jonas\\Music",
      "C:\\Users\\Jonas\\Music\\",
      musicFolder.Path,
      testFolder.Path,
      appFolder.Path
   };
   foreach(string path in paths)
   {
      GetDiskFreeSpaceExW(path, out a, out b, out c);
      int error = GetLastError();
      Debug.WriteLine(
         string.Format("{0} - Error {1} - free = {2}",
         path ?? "null", error, a));
   }
}

Debug output:

null - Error 5 - free = 0
. - Error 123 - free = 0
C: - Error 3 - free = 0
C:\ - Error 3 - free = 0
C:\Users\J909\Music - Error 3 - free = 0
C:\Users\J909\Music\ - Error 3 - free = 0
 - Error 3 - free = 0
C:\Users\J909\Music\test - Error 123 - free = 0
C:\Users\J909\AppData\Local\Packages\long-app-id\LocalState - Error 123 - free = 0

It seems I am providing the wrong input. Error codes: 3: ERROR_PATH_NOT_FOUND, 5: ERROR_ACCESS_DENIED, 123: ERROR_INVALID_NAME. I am running this code on Windows 8 RP (x64) with VS Ultimate 2012 RC called from a Metro style application. My application was granted access to the user's music library.

- Metro-? ?

0
2

Win32 COM Metro. GetDiskFreeSpaceExW, , ​​ , P/Invoke, GetDiskFreeSpaceEx:

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

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));
}
+4

long free = new DriveInfo(driveName).TotalFreeSpace;
0

All Articles