C # How to obtain the remaining disk space

Source: Internet
Author: User

Using system;
Using system. Management;

...

Managementobject disk = new
Managementobject ("win32_logicaldisk.deviceid =" C :"");
Disk. Get ();
Console. writeline ("Logical Disk size =" + disk ["size"] + "bytes ");
Console. writeline ("Logical Disk freespace =" + disk ["freespace"] +"
Bytes ");

Drive Free Space

There are several ways to get the drive free space:

1. The InterOP way.

Using system. runtime. interopservices;

[Dllimport ("kernel32.dll")]
Public static extern bool getdiskfreespaceex (
String lpdirectoryname,
Out uint64 lpfreebytesavailable,
Out uint64 lptotalnumberofbytes,
Out uint64 lptotalnumberoffreebytes );

Ulong freebytesavailable = 0;
Ulong totalnumberofbytes = 0;
Ulong totalnumberoffreebytes = 0;

Getdiskfreespaceex (
"C :\\",
Out freebytesavailable,
Out totalnumberofbytes,
Out totalnumberoffreebytes );

2. the WMI way

We can use WMI by connecting to the "Root \ cimv2" namespace and using the "win32_logicaldisk" class. programming WMI isn't pretty, but you can use the WMI extensions for vs '03 Server Explorer which makes it tolerable. once installed, you'll get a list of the management classes in Server Explorer and you can simply drag and drop the disk volume that you want to pull information from onto your Application Designer.

You can then show free space on the volume with one line of code: MessageBox. Show (logicaldisk1.freespace. tostring ());

Using system;
Using system. Management;

Tatic void main (string [] ARGs)
{
Wqlobjectquery wmiquery = new wqlobjectquery ("select * From win32_logicaldisk where DeviceID = 'C :'");
Managementobjectsearcher wmifind = new managementobjectsearcher (wmiquery );

Foreach (managementobject mobj in wmifind. Get ())
{
Console. writeline ("Description:" + mobj ["Description"]);
Console. writeline ("File System:" + mobj ["filesystem"]);
Console. writeline ("free disk space:" + mobj ["freespace"]);
Console. writeline ("Size:" + mobj ["size"]);
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.