我正在编写Metro风格的应用程序,并希望确定托管用户音乐库的驱动器的可用存储容量。我想禁用一些应用程序功能,而磁盘上没有剩余空间或很少空间。我正在使用P / Invoke来调用GetDiskFreeSpaceExW并获取错误并且没有有效的字节数。
[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));
}
}
调试输出:
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
看来我提供了错误的输入。错误代码为3:ERROR_PATH_NOT_FOUND,5:ERROR_ACCESS_DENIED,123:ERROR_INVALID_NAME。我在带有VS Ultimate 2012 RC的Windows 8 RP(x64)上运行此代码,这是来自Metro风格的应用程序。我的应用程序被授予访问用户音乐库的权限。
有人设法在Metro风格的应用程序中成功调用此功能吗?接受什么样的目录名来产生有效的可用空间读数?
答案 0 :(得分:4)
我根据Win32 and COM documentation for Metro在此问题中创建了代码。它调用GetDiskFreeSpaceExW在metro中可用,但使用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));
}
答案 1 :(得分:0)
你可能会有更好的运气
long free = new DriveInfo(driveName).TotalFreeSpace;