long mb = 1048576; //megabyte in # of bytes 1024×1024

//Connection credentials to the remote computer – not needed if the logged in account has access

ConnectionOptions coConnectionOption = new ConnectionOptions();

ManagementScope msScope;

if (chkLocal.Checked)

{

//If the local machine is selected

msScope = new ManagementScope("\\" + Environment.MachineName + "\root\CIMV2", coConnectionOption);

}

else

{

//required for a system in network

coConnectionOption.Username = txtUserName.Text.Trim();

coConnectionOption.Password = txtPassword.Text.Trim();

msScope = new ManagementScope("\\" + cmbHostNames.SelectedItem.ToString().Trim() + "\root\CIMV2", coConnectionOption);

}

//get Fixed disk stats

ObjectQuery oqQuery = new ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3");

ManagementObjectSearcher mosSearcher = new ManagementObjectSearcher(msScope, oqQuery);

ManagementObjectCollection mocQueryCollection = mosSearcher.Get();

//variables for numerical conversions

double dblFreeSpace = 0;

double dblUsedSpace = 0;

double dblTotalSpace = 0;

double dblUsedPercentage = 0;

double dblFreePercentage = 0;

DataTable dtHardDiskSpace = new DataTable();

string[] strColumnnames = { "Drive Name", "Total Space", "Used Space", "Used Percentage", "Free Space", "Free Percentage" };

foreach (string strColumn in strColumnnames)

{

dtHardDiskSpace.Columns.Add(new DataColumn(strColumn));

}

//loop through found drives and write out info

foreach (ManagementObject oReturn in mocQueryCollection)

{

//Free space in MB

dblFreeSpace = Convert.ToInt64(oReturn["FreeSpace"]) / mb;

//Used space in MB

dblUsedSpace = (Convert.ToInt64(oReturn["Size"]) – Convert.ToInt64(oReturn["FreeSpace"])) / mb;

//Total space in MB

dblTotalSpace = Convert.ToInt64(oReturn["Size"]) / mb;

//used percentage

dblUsedPercentage = dblUsedSpace / dblTotalSpace * 100;

//free percentage

dblFreePercentage = dblFreeSpace / dblTotalSpace * 100;

//write out used space stats

DataRow drNewRow = dtHardDiskSpace.NewRow();

//Console.WriteLine("totalSpace "+ totalSpace);

drNewRow["Drive Name"] = oReturn["Name"].ToString();

drNewRow["Total Space"] = dblTotalSpace.ToString("#,###.##") + " MB";

drNewRow["Used Space"] = dblUsedSpace.ToString("#,###.##") + " MB";

drNewRow["Used Percentage"] = dblUsedPercentage.ToString("##.##") + " %";

drNewRow["Free Space"] = dblFreeSpace.ToString("#,###.##") + " MB";

drNewRow["Free Percentage"] = dblFreePercentage.ToString("##.##") + " %";

dtHardDiskSpace.Rows.Add(drNewRow);

}

dataGridView1.DataSource = dtHardDiskSpace;

Advertisements