1. 程式人生 > >C# 獲取磁碟空間資訊

C# 獲取磁碟空間資訊

獲取本地或遠端伺服器磁碟用度,示例如下

1.獲取本機磁碟用度

  可通過 DriveInfo 或ManagementObjectSearcher兩種方式

  A.DriveInfo 

 public void GetDriver()
        {            
            long lsum = 0, ldr = 0;
            long gb = 1024 * 1024 * 1024;

            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                //判斷是否是固定磁碟
                if (drive.DriveType == DriveType.Fixed)
                {
                    lsum = drive.TotalSize / gb;
                    ldr = drive.TotalFreeSpace / gb;
                    richTextBox1.Text += drive.Name + ": 總空間=" + lsum.ToString() + " 剩餘空間=" + ldr.ToString()+"\n\r";
                }                
            }
            //progressBar1.Value = int.Parse((lsum - ldr).ToString());
            //progressBar1.Maximum = int.Parse(lsum.ToString());
            //lbMsg.Text = "磁碟" + disksrc + "的可用空間為" + ldr + "GB!";
        }

 B.ManagementObjectSearcher

需引入名稱空間:using System.Management;(同時在專案中,通過新增引用方式新增)
public void GetDriveInfoDetail(string driveName)
        {
            WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_LogicalDisk WHERE DeviceID = '{0}'", driveName.Substring(0, 2)));

            ManagementObjectSearcher managerSearch = new ManagementObjectSearcher(wqlObjectQuery);

            List<ulong> driveInfoList = new List<ulong>(2);

            foreach (ManagementObject mobj in managerSearch.Get())
            {
                richTextBox1.Text += "Description: " + mobj["Description"] + "\r\n";
                richTextBox1.Text += "File system: " + mobj["FileSystem"] + "\r\n";
                richTextBox1.Text += "Free disk space: " + mobj["FreeSpace"] + "\r\n";
                richTextBox1.Text += "Size: " + mobj["Size"] + "\r\n";
            }

        }
呼叫示例:<pre name="code" class="csharp">GetDriveInfoDetail("D:");//注意碟符後要有:號

2.獲取遠端伺服器磁碟用度

 private void button2_Click(object sender, EventArgs e)
        {
            string ip = textBoxSrcPath.Text;//"172.16.5.214";

            string disksrc = textBoxDirPath.Text + ":";//"D:";

            string username = txtUsername.Text;//"Administrator"; //

            string password = txtPassword.Text;//"password";


            long freesize = 0, size = 0;

            long gb = 1024 * 1024 * 1024;

            ConnectionOptions connectionOptions = new ConnectionOptions();

            connectionOptions.Username = username;

            connectionOptions.Password = password;

            connectionOptions.Timeout = new TimeSpan(1, 1, 1, 1);//連線時間



            //ManagementScope 的伺服器和名稱空間。

            string path = string.Format("\\\\{0}\\root\\cimv2", ip);

            //表示管理操作的範圍(名稱空間),使用指定選項初始化ManagementScope 類的、表示指定範圍路徑的新例項。

            ManagementScope scope = new ManagementScope(path, connectionOptions);

            scope.Connect();

            //查詢字串,某磁碟上資訊

            string strQuery = string.Format("select * from Win32_LogicalDisk where deviceid='{0}'", disksrc);
            

            ObjectQuery query = new ObjectQuery(strQuery);

            //查詢ManagementObjectCollection返回結果集
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

            foreach (ManagementObject m in searcher.Get())
            {
                if (m["Name"].ToString() == disksrc)
                {   //通過m["屬性名"]
                    freesize = Convert.ToInt64(m["FreeSpace"]) / gb;
                    size = Convert.ToInt64(m["Size"]) / gb;
                }
            }
            txtdr.Text = freesize.ToString();
            if (freesize <= 20)
            {
                lbMsg.ForeColor = Color.Red;
                lbMsg.Text = "磁碟" + disksrc + "的可用空間為" + freesize + "GB,請及時清理!";
            }

            progressBar1.Maximum = int.Parse(size.ToString());
            progressBar1.Value = int.Parse((size - freesize).ToString());

            lbMsg.Text = "磁碟" + disksrc + "的可用空間為" + freesize + "GB!";            
        }