I had the same problem and i saw waruna manjula giving the best answer.
However writing it all down on the console is not what you might want.
To get string off al info use the following
Step one: declare values at begin
//drive 1
public static string drivename = "";
public static string drivetype = "";
public static string drivevolumelabel = "";
public static string drivefilesystem = "";
public static string driveuseravailablespace = "";
public static string driveavailablespace = "";
public static string drivetotalspace = "";
//drive 2
public static string drivename2 = "";
public static string drivetype2 = "";
public static string drivevolumelabel2 = "";
public static string drivefilesystem2 = "";
public static string driveuseravailablespace2 = "";
public static string driveavailablespace2 = "";
public static string drivetotalspace2 = "";
//drive 3
public static string drivename3 = "";
public static string drivetype3 = "";
public static string drivevolumelabel3 = "";
public static string drivefilesystem3 = "";
public static string driveuseravailablespace3 = "";
public static string driveavailablespace3 = "";
public static string drivetotalspace3 = "";
Step 2: actual code
DriveInfo[] allDrives = DriveInfo.GetDrives();
int drive = 1;
foreach (DriveInfo d in allDrives)
{
if (drive == 1)
{
drivename = String.Format("Drive {0}", d.Name);
drivetype = String.Format("Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
drivevolumelabel = String.Format("Volume label: {0}", d.VolumeLabel);
drivefilesystem = String.Format("File system: {0}", d.DriveFormat);
driveuseravailablespace = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
driveavailablespace = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
drivetotalspace = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
}
drive = 2;
}
else if (drive == 2)
{
drivename2 = String.Format("Drive {0}", d.Name);
drivetype2 = String.Format("Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
drivevolumelabel2 = String.Format("Volume label: {0}", d.VolumeLabel);
drivefilesystem2 = String.Format("File system: {0}", d.DriveFormat);
driveuseravailablespace2 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
driveavailablespace2 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
drivetotalspace2 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
}
drive = 3;
}
else if (drive == 3)
{
drivename3 = String.Format("Drive {0}", d.Name);
drivetype3 = String.Format("Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
drivevolumelabel3 = String.Format("Volume label: {0}", d.VolumeLabel);
drivefilesystem3 = String.Format("File system: {0}", d.DriveFormat);
driveuseravailablespace3 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
driveavailablespace3 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
drivetotalspace3 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
}
drive = 4;
}
if (drive == 4)
{
drive = 1;
}
}
//part 2: possible debug - displays in output
//drive 1
Console.WriteLine(drivename);
Console.WriteLine(drivetype);
Console.WriteLine(drivevolumelabel);
Console.WriteLine(drivefilesystem);
Console.WriteLine(driveuseravailablespace);
Console.WriteLine(driveavailablespace);
Console.WriteLine(drivetotalspace);
//drive 2
Console.WriteLine(drivename2);
Console.WriteLine(drivetype2);
Console.WriteLine(drivevolumelabel2);
Console.WriteLine(drivefilesystem2);
Console.WriteLine(driveuseravailablespace2);
Console.WriteLine(driveavailablespace2);
Console.WriteLine(drivetotalspace2);
//drive 3
Console.WriteLine(drivename3);
Console.WriteLine(drivetype3);
Console.WriteLine(drivevolumelabel3);
Console.WriteLine(drivefilesystem3);
Console.WriteLine(driveuseravailablespace3);
Console.WriteLine(driveavailablespace3);
Console.WriteLine(drivetotalspace3);
I want to note that you can just make all the console writelines comment code, but i thought it would be nice for you to test it.
If you display all these after each other you get the same list as waruna majuna
Drive C:
Drive type: Fixed
Volume label:
File system: NTFS
Available space to current user: 134880153600 bytes
Total available space: 134880153600 bytes
Total size of drive: 499554185216 bytes
Drive D:
Drive type: CDRom
Drive H:
Drive type: Fixed
Volume label: HDD
File system: NTFS
Available space to current user: 2000010817536 bytes
Total available space: 2000010817536 bytes
Total size of drive: 2000263573504 bytes
However you can now acces all of the loose information at strings
When our C# application fetches computer drive information, data about the disk’s size and free space is returned in bytes. While precise, those values are not easy to read and understand for our users. Other ways to show disk information is the percentage of free disk space or to report sizes in megabytes (MBs) or gigabytes (GBs). Let’s see how we get those values in C#.
IN THIS ARTICLE:
# Access drive information and disk capacity with C# code
To get drive information in our C# application we use the DriveInfo
class from the System.IO
namespace (Asad & Ali, 2017; Stephens, 2014). A single DriveInfo
object models one computer drive (Stephens, 2014). Through that object we can access the drive’s information, like its name label, type of drive, and the drive’s root directory.
Other data we can fetch from the DriveInfo
class is the drive’s capacity, like free space amount or total size. We use the following three properties for that (Microsoft Docs, n.d.; Stephens, 2014):
- The
AvailableFreeSpace
returns the drive’s available free space in bytes. - The
TotalFreeSpace
property returns the drive’s total free space. - And the
TotalSize
property returns the drive’s total capacity (that is, used and free space) in bytes.
To make sense of the above three properties and see how we can use them in our application’s code, let’s explore two examples. The first console application below calculates the percentage of free disk space a drive has. In the second example we convert a drive’s free disk space in bytes into megabytes (MBs) and gigabytes (GBs).
# Example: calculate the free disk space percentage in C#
To calculate the percentage of free space a computer drive has, we have to do a couple of things:
- Create an instance for that drive with the
DriveInfo
class from theSystem.IO
namespace. - Fetch the drive’s total size, which we get with the
TotalSize
property from that class. - Then get the drive’s free space, for which we can use the
AvailableFreeSpace
property. - After that we divide the free space by the drive’s total size to see what percentage of free disk space we have.
The console application example below shows how we implement these steps in C# code:
using System;
using System.IO;
class Kodify_Example
{
static void Main()
{
// Create a DriveInfo instance of the D: drive
DriveInfo dDrive = new DriveInfo("D");
// When the drive is accessible..
if (dDrive.IsReady)
{
// Calculate the percentage free space
double freeSpacePerc =
(dDrive.AvailableFreeSpace / (float)dDrive.TotalSize) * 100;
// Ouput drive information
Console.WriteLine("Drive: {0} ({1}, {2})",
dDrive.Name, dDrive.DriveFormat, dDrive.DriveType);
Console.WriteLine("tFree space:t{0}",
dDrive.AvailableFreeSpace);
Console.WriteLine("tTotal space:t{0}",
dDrive.TotalSize);
Console.WriteLine("ntPercentage free space: {0:0.00}%.",
freeSpacePerc);
}
Console.WriteLine("nPress a key to close this window..");
Console.ReadKey();
}
}
On my computer this example program shows that the D: drive has just over two thirds of free space:
Drive: D: (NTFS, Fixed)
Free space: 167283777536
Total space: 250056704000
Percentage free space: 66,90%.
Press a key to close this window..
Now let’s see how we got this output. First we make an instance of the DriveInfo
class for the D: drive:
DriveInfo dDrive = new DriveInfo("D");
Then we check whether the computer drive is ready with an if statement. If it is, we query the drive’s properties for information:
if (dDrive.IsReady)
{
double freeSpacePerc =
(dDrive.AvailableFreeSpace / (float)dDrive.TotalSize) * 100;
Console.WriteLine("Drive: {0} ({1}, {2})",
dDrive.Name, dDrive.DriveFormat, dDrive.DriveType);
Console.WriteLine("tFree space:t{0}",
dDrive.AvailableFreeSpace);
Console.WriteLine("tTotal space:t{0}",
dDrive.TotalSize);
Console.WriteLine("ntPercentage free space: {0:0.00}%.",
freeSpacePerc);
}
The IsReady
property returns true
when a drive is ready and accessible. We check its value before we fetch other DriveInfo
properties because some of those properties depend on a ready drive. If the drive is not ready to be queried, those properties trigger an inaccessible drive exception.
The first thing we do inside the if statement is calculate the percentage of free disk space. For that we divide the drive’s available free space (AvailableFreeSpace
) with its total size (TotalSize
). Then we multiple that value with 100 to get the percentage, and then store it in the freeSpacePerc
double
variable.
Note that we explicitly cast the TotalSize
property to a float
value. The reason for this is that both AvailableFreeSpace
and TotalSize
return an integer, and with integer division C# throws away the remainder of division (Liberty & MacDonald, 2009). Else when AvailableFreeSpace / TotalSize
would normally be 0.45
, C# returns 0
instead.
After we calculated the percentage of free space we call the Console.WriteLine()
method to print the drive’s name (Name
), file system format (DriveFormat
), and kind of drive (DriveType
). We also output the number of bytes returned by the AvailableFreeSpace
and TotalSize
properties. Then in the last line of the if statement we print the percentage of free disk space (freeSpacePerc
).
# Example method to calculate the free disk space
When we calculate the percentage of free space more than once in our application, writing the above code over and over becomes a bore. Plus it doesn’t give code that’s easy to maintain. An alternative is to rewrite the code into a method that we can simply call to get a drive’s free space percentage.
Here’s how that method can look:
private double PercentageFreeSpace(string driveLetter)
{
try
{
DriveInfo drive = new DriveInfo(driveLetter);
return (drive.AvailableFreeSpace / (double)drive.TotalSize) * 100;
}
catch
{
// Return -1 when the drive is not accessible (gives an `IOException`)
// or when the drive letter is invalid, in which case `DriveInfo()` generates
// an error of type `ArgumentException`.
return -1;
}
}
This method returns the percentage of free space for the driveLetter
string argument we pass it. Inside the method there’s a try/catch code to block handle inaccessible computer drives. In the try
portion we make an instance of the DriveInfo
class with DriveInfo()
. Then we calculate that drive’s percentage of free space and return the outcome.
By the way, this method does assume that your code already referenced the System.IO
namespace. If that isn’t the case, you’ll need to prefix the DriveInfo
class with that namespace.
Here’s how we use this method to get the free space percentage of the C: drive:
Console.WriteLine("Free space % of C: " + PercentageFreeSpace("C"));
# Example extension method to calculate the percentage of free space
An alternative to the above method is to create an extension method that returns the percentage of free a particular DriveInfo
instance has. That makes it possible to fetch a drive’s free disk space like any other property from the DriveInfo
class.
Here’s how such an extension method looks:
public static class MyExtensions
{
public static double FreeSpacePercentage(this DriveInfo drive)
{
return (drive.AvailableFreeSpace / (double)drive.TotalSize) * 100;
}
}
To use this method we first create a DriveInfo
object. Then we call that method on the object, provided the drive is ready:
DriveInfo dDrive = new DriveInfo("D");
if (dDrive.IsReady)
{
Console.WriteLine("Percentage of free space on D: {0}",
dDrive.FreeSpacePercentage());
}
# Example: calculate a drive’s disk space in GBs and MBs
Let’s look at another way to use a drive’s space information. The AvailableFreeSpace
, TotalFreeSpace
, and TotalSize
properties from the DriveInfo
class return their values in bytes (Microsoft Docs, n.d.). But easier-to-understand values would be megabytes (MBs) and gigabytes (GBs). So let’s turn those bytes into MBs and GBs.
To go from bytes to other measurement units for computer space, we’ll need to consider the following (Wikipedia, 2017):
- One terabyte (TB) is 1024 gigabytes. One of those gigabytes (GBs) is 1024 megabytes big. A single megabyte (MB) is 1024 kilobytes. And each kilobyte (KB) contains 1024 bytes.
- Or in other words: 1 terabyte contains 1024^4 bytes. One gigabyte holds 1024^3 bytes, and 1024^2 bytes go into a single megabyte. And a single kilobyte contains 1024 bytes.
Say our computer drive has 20,000,000 bytes of free space. Because 1,048,576 (1024 * 1024) bytes go in a megabyte, our disk has 20,000,000 / 1,048,576 = 19.07 MB of free disk space. In the same way we can calculate how many kilobytes, gigabytes, and terabytes there are in a certain amount of bytes.
Now let’s translate this information into actual C# code. The console application example below outputs a drive’s used and total space in GBs and MBs:
using System;
using System.IO;
class Kodify_Example
{
static void Main()
{
// We use these constants to convert bytes to megabytes and gigabytes
const double BytesInMB = 1048576;
const double BytesInGB = 1073741824;
Console.WriteLine("Computer drive sizes in MBs and GBs:");
// Go through each of the computer's drives
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
// Skip to next loop cycle when drive is not ready
if (!drive.IsReady)
continue;
Console.WriteLine("nDrive: {0} ({1}, {2})",
drive.Name, drive.DriveType, drive.DriveFormat);
// Show the used and total size in MB and GB, with two decimals
Console.WriteLine(" Used space:t{0:0.00} MBt{1:0.00} GB",
(drive.TotalSize - drive.TotalFreeSpace) / BytesInMB,
(drive.TotalSize - drive.TotalFreeSpace) / BytesInGB);
Console.WriteLine(" Total size:t{0:0.00} MBt{1:0.00} GB",
drive.TotalSize / BytesInMB,
drive.TotalSize / BytesInGB);
}
Console.WriteLine("nPress a key to close this window..");
Console.ReadKey();
}
}
The output that this application generates on my computer is:
Computer drive sizes in MBs and GBs:
Drive: C: (Fixed, NTFS)
Used space: 102195,07 MB 99,80 GB
Total size: 114371,00 MB 111,69 GB
Drive: D: (Fixed, NTFS)
Used space: 78949,86 MB 77,10 GB
Total size: 238472,66 MB 232,88 GB
Drive: E: (Removable, FAT32)
Used space: 94,72 MB 0,09 GB
Total size: 242,53 MB 0,24 GB
Press a key to close this window..
Now let’s explore the program’s code. First we make two constants:
const double BytesInMB = 1048576;
const double BytesInGB = 1073741824;
The BytesInMB
constant tells how many bytes go in a megabyte, while BytesInGB
says how many bytes we need for one GB.
We declare these constants as double
values even though they hold integers. We do so because we’ll use these values later when we divide an integer value. And when we divide two integers, C# throws away the fractional portion of the outcome. To prevent that from happening we make double
constants instead of int
ones.
The next piece of program code iterates through the computer’s drives:
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (!drive.IsReady)
continue;
Console.WriteLine("nDrive: {0} ({1}, {2})",
drive.Name, drive.DriveType, drive.DriveFormat);
Console.WriteLine(" Used space:t{0:0.00} MBt{1:0.00} GB",
(drive.TotalSize - drive.TotalFreeSpace) / BytesInMB,
(drive.TotalSize - drive.TotalFreeSpace) / BytesInGB);
Console.WriteLine(" Total size:t{0:0.00} MBt{1:0.00} GB",
drive.TotalSize / BytesInMB,
drive.TotalSize / BytesInGB);
}
This foreach
loop goes through all elements returned by DriveInfo.GetDrives()
. That method returns an array with all drives the computer has. With the drive
DriveInfo
loop variable we represent a single drive during each iteration through the loop.
In the loop we first have an if statement see whether the current drive is not (!
) ready. We get that drive state with the IsReady
property. When the drive is not ready to be queried and accessed, we execute the continue
keyword to skip the current loop cycle. That also means that later code in the loop works with a ready computer drive.
That other code first has the Console.WriteLine()
method print the drive’s name (Name
), kind of drive (DriveType
), and its file system format (DriveFormat
).
Then we output the drive’s used space in MBs and GBs. After that we output the drive’s used space in MBs and GBs. For that we first subtract the drive’s free space (TotalFreeSpace
) from its total size (TotalSize
). Then we divide that byte amount with the BytesInMB
or BytesInGB
constant. Next we have Console.WriteLine()
print those used disk spaces with two decimals.
The last bit of loop code output the drive’s total size. For that we divide the drive’s TotalSize
property with the BytesInMB
or BytesInGB
constant to get the total space in MBs and GBs. Then we print that information to the console window with Console.WriteLine()
.
# Summary
We access computer drive information in C# with an instance of the DriveInfo
class. Once we have such an object we can query various properties for drive information. TotalSize
, for instance, returns the drive’s total capacity in bytes. And with the AvailableFreeSpace
and TotalFreeSpace
properties we get the drive’s free space in bytes.
A large bytes value is, however, hard to read and comprehend. Luckily we can also represent a drive’s space in other ways. To see a computer drive’s free space percentage we divide AvailableFreeSpace
with TotalSize
. And to know the number of megabytes (MBs) or gigabytes (GBs) used we can divide one of those DriveInfo
properties with 1,048,576 or 1,073,741,824. Keep in mind that when we divide two integers, C# throws away the decimal value. The solution to that is to cast to a float
or double
.
References
Asad, A. & Ali, H. (2017). The C# Programmer’s Study Guide (MCSD). New York, NY: Apress.
Liberty, J. & MacDonald, B. (2009). Learning C# 3.0: Master the Fundamentals of C# 3.0. Sebastopol, CA: O’Reilly Media.
Microsoft Docs (n.d.). DriveInfo Class. Retrieved on November 9, 2017, from https://docs.microsoft.com/en-us/dotnet/api/system.io.driveinfo?view=netframework-4.7.1
Stephens, R. (2014). C# 5.0 Programmer Reference. Indianapolis, IN: John Wiley & Sons.
Wikipedia (2017, November 23). Binary prefix. Retrieved on November 30, 2017, from https://en.wikipedia.org/wiki/Binary_prefix
Last updated on December 1, 2018
(published December 30, 2017).
« All C# computer drives articles
You can use the following Win32 API function to get the free disk space in C++. Note that this function can be used with Qt for Windows if you add the required dependencies described in this post.
First of all you need to add the following to your Qt project file (.PRO file)
LIBS += -lkernel32
Next, you have to include “Windows.h” file in your header file.
#include "Windows.h"
Now you can use the following function to get the remaining free disk space in the main hard disk partition, in terms of percentage. Notice that you can also use lpSectorsPerCluster, lpBytesPerSector, lpNumberOfFreeClusters and lpTotalNumberOfClusters to get even more detailed information about the disk.
Also by providing any path or disk address other than NULL to the first parameter of GetDiskFreeSpace function below (the function used in the if clause below) you can get information about other partitions.
int getDiskFreeSpacePercentage()
{
DWORD lpSectorsPerCluster,
lpBytesPerSector,
lpNumberOfFreeClusters,
lpTotalNumberOfClusters;
if (GetDiskFreeSpace(NULL,
&lpSectorsPerCluster,
&lpBytesPerSector,
&lpNumberOfFreeClusters,
&lpTotalNumberOfClusters))
{
return int(double(lpNumberOfFreeClusters) / double(lpTotalNumberOfClusters) * 100.0);
}
else
{
return 0;
}
}
DriveInfo Class
Being able to determine the amount of space not in use on a particular drive from C# code is very easy and straight forward. Various properties relating to a logical Windows drive can be determined by implementing the System.IO.DriveInfo class.
The DriveInfo class exposes two public properties relating to drive space not in use:
- System.IO.DriveInfo.AvailableFreeSpace
- System.IO.DriveInfo.TotalFreeSpace
The difference between these two properties is that AvailableFreeSpace takes into account user configured disk quotas in Windows. AvailableFreeSpace therefore represents the total amount of free space available to the currently logged in user. In contrast TotalFreeSpace represents the total amount of space free on the specified drive, regardless of restrictions/quotas on the currently logged in user’s account.
To be safe use AvailableFreeSpace when doing file IO operations such as copying, downloading or creating new files.
I have written an example application that implements two extension methods which allows the calling code to specify the measurement unit (Bytes, Kilobytes, Megabytes, Gigabytes and Terabytes) in which to return TotalFreeSpace or AvailableFreeSpace.
Code Sample
Download the source code here
This code sample implements the DriveInfo Class’ AvailableFreeSpace and TotalFreeSpace properties and creates two extension methods allowing the calling code to specify the measurement unit (Bytes, Kilobytes, Megabytes, Gigabytes and Terabytes)
DiskSizeUnit enum
Both extension methods expects as a parameter an enum value of type DiskSizeUnit. The value will determine the unit in which AvailableFreeSpace or TotalFreeSpace gets returned.
1: public enum DiskSizeUnit
2: {
3: Bytes = 0,
4: KiloBytes = 1,
5: MegaBytes = 2,
6: GigaBytes = 3,
7: TeraBytes = 4
8: }
9:
Total Free Space
The TotalFreeSpaceFormatted extension method accepts as its first parameter an object of type DriveInfo, indicating that this method acts as an extension method to the DriveInfo Class. The second parameter is an enum instance of type DiskSizeUnit, which is used to determine the measurement unit in which to return the DriveInfo class’ TotalFreeSpace property.
1: public static double TotalFreeSpaceFormatted(this DriveInfo driveInfo, DiskSizeUnit sizeUnit)
2: {
3: double freeSpace = -1;
4: double formatDivideBy = 1;
5:
6: if (driveInfo != null )
7: {
8: long freeSpaceNative = driveInfo.TotalFreeSpace;
9: formatDivideBy = Math.Pow(1024, (int )sizeUnit);
10:
11: freeSpace = freeSpaceNative / formatDivideBy;
12: }
13:
14: return freeSpace;
15: }
The method first checks if the DriveInfo object has been instantiated (line 6). In order to convert TotalFreeSpace, which is expressed in bytes, the value is divided based on the value of the DiskSizeUnit enum parameter passed to this method. As an example if DiskSizeUnit.MegaBytes is specified, the Math.Pow() method will return 1048576 (1024 * 1024), as shown on line 9. Dividing a value expressed in bytes by 1024 and again by 1024 will return a value representing the original byte value expressed in megabytes.
Note: DriveInfo.TotalFreeSpace will return the number of bytes not in use on a particular drive. This property does not take into account limitations/restrictions on the currently logged in user such as Disk Quotas defined by Windows User Accounts.
Available Free Space
The AvailableFreeSpaceFormatted extension method accepts as its first parameter an object of type DriveInfo, indicating that this method acts as an extension method to the DriveInfo Class. The second parameter is an enum instance of type DiskSizeUnit, which is used to determine the measurement unit in which to return the DriveInfo class’ AvailableFreeSpace property.
1: public static double AvailableFreeSpaceFormatted(this DriveInfo driveInfo, DiskSizeUnit sizeUnit)
2: {
3: double freeSpace = -1;
4: double formatDivideBy = 1;
5:
6: if (driveInfo != null )
7: {
8: long freeSpaceNative = driveInfo.AvailableFreeSpace;
9: formatDivideBy = Math .Pow(1024, (int )sizeUnit);
10:
11: freeSpace = freeSpaceNative / formatDivideBy;
12: }
13:
14: return freeSpace;
15: }
Internally this method works almost exactly the same as the TotalFreeSpaceFormatted extension method. The only difference being checking and formatting through division the DriveInfo.AvailableFreeSpace property.
Note: DriveInfo.AvailableFreeSpace takes into account limitations/restrictions on the currently logged in user’s account such as Disk Quotas defined by Windows User Accounts.
Test Application
As part of this code sample a Console based test application is provided.
The test application determines the drive letter of the current directory using Environment.CurrentDirectory and Path.GetPathRoot.
1: if (Environment .CurrentDirectory != String .Empty)
2: {
3: string driveLetter = Path .GetPathRoot(Environment .CurrentDirectory);
4:
5: DriveInfo drive = new DriveInfo (driveLetter);
6:
7: Console .WriteLine("TotalFreeSpace: {0,0:F3} B" ,
8: drive.TotalFreeSpace);
9:
10: Console .WriteLine();
11: Console .WriteLine("TotalFreeSpaceFormatted:" );
12:
13: Console .WriteLine("{0,0:F3} B" ,
14: drive.TotalFreeSpaceFormatted(DiskSizeUnit .Bytes));
15:
16: Console .WriteLine("{0,0:F3} KB" ,
17: drive.TotalFreeSpaceFormatted(DiskSizeUnit .KiloBytes));
18:
19: Console .WriteLine("{0,0:F3} MB" ,
20: drive.TotalFreeSpaceFormatted(DiskSizeUnit .MegaBytes));
21:
22: Console .WriteLine("{0,0:F3} GB" ,
23: drive.TotalFreeSpaceFormatted(DiskSizeUnit .GigaBytes));
24:
25: Console .WriteLine("{0,0:F3} TB" ,
26: drive.TotalFreeSpaceFormatted(DiskSizeUnit .TeraBytes));
27:
28: Console .WriteLine();
29:
30: Console .WriteLine("TotalFreeSpace: {0,0:F3} B" ,
31: drive.AvailableFreeSpace);
32:
33: Console .WriteLine();
34: Console .WriteLine("AvailableFreeSpaceFormatted:" );
35:
36: Console .WriteLine("{0,0:F3} B" ,
37: drive.AvailableFreeSpaceFormatted(DiskSizeUnit .Bytes));
38:
39: Console .WriteLine("{0,0:F3} KB" ,
40: drive.AvailableFreeSpaceFormatted(DiskSizeUnit .KiloBytes));
41:
42: Console .WriteLine("{0,0:F3} MB" ,
43: drive.AvailableFreeSpaceFormatted(DiskSizeUnit .MegaBytes));
44:
45: Console .WriteLine("{0,0:F3} GB" ,
46: drive.AvailableFreeSpaceFormatted(DiskSizeUnit .GigaBytes));
47:
48: Console .WriteLine("{0,0:F3} TB" ,
49: drive.AvailableFreeSpaceFormatted(DiskSizeUnit .TeraBytes));
50: }
51:
52: Console .WriteLine();
53: Console .WriteLine("Press any key to exit" );
54: Console .ReadKey();
55:
*I want to give credit and say a big thank you to Vitaly Zayko. All the code snippets Html markup in this article was generated using his Visual Studio Extension Code4Blog.
- Remove From My Forums
-
Question
-
How to get free Hard disk drive space in C# store app?
Answers
-
you wont have access to that information. The app runs in a sandbox
-
Marked as answer by
Friday, March 1, 2013 12:33 PM
-
Marked as answer by
-
Running on 8.1 this works fine:
protected override void OnNavigatedTo(NavigationEventArgs e) { string DirectoryName = @"C:"; ulong FreeBytesAvailable = 0; ulong TotalNumberOfBytes = 0; ulong TotalNumberOfFreeBytes = 0; GetDiskFreeSpaceEx(DirectoryName, out FreeBytesAvailable, out TotalNumberOfBytes, out TotalNumberOfFreeBytes); MyTextBox.Text += "DirectoryName: " + DirectoryName + "rn"; MyTextBox.Text += "FreeBytesAvailable: " + FreeBytesAvailable.ToString() + "rn"; MyTextBox.Text += "TotalNumberOfBytes: " + TotalNumberOfBytes.ToString() + "rn"; MyTextBox.Text += "TotalNumberOfFreeBytes: " + TotalNumberOfFreeBytes.ToString() + "rn"; } [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes);
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <TextBox Width="500" Height="800" x:Name="MyTextBox" Background="White" AcceptsReturn="True"/> </Grid>
Matt Small — Microsoft Escalation Engineer — Forum Moderator
If my reply answers your question, please mark this post as answered.NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I’m trying to help a lot of people, so I don’t have time to figure out weird snippets with undefined
objects and unknown namespaces.-
Marked as answer by
Matt SmallMicrosoft employee, Moderator
Tuesday, March 18, 2014 3:55 PM
-
Marked as answer by