• 當前位置:首頁 > IT技術 > Windows編程 > 正文

    C#獲取本地或遠程磁盤使用信息
    2021-10-22 09:52:08

    因為公司有多個服務器,要檢查磁盤的使用情況確定程序放哪個服務器和清理垃圾,所以寫個小程序幫忙檢查。

    效果圖:

    C#獲取本地或遠程磁盤使用信息_檢查磁盤使用

    ?

    C#獲取本地或遠程磁盤使用信息_檢查磁盤使用_02

    后臺代碼:



    private void btnCheck_Click(object sender, EventArgs e)
    {
    listBox1.Items.Clear();
    if (rbtnRemote.Checked)
    {
    //遠程
    RemoteDisk();
    }
    else
    {
    //本地
    LocalDisk();
    }
    }
    //查看本地
    private void LocalDisk()
    {
    WqlObjectQuery wmiquery = new WqlObjectQuery("select * from Win32_LogiCalDisk");
    ManagementObjectSearcher wmifind = new ManagementObjectSearcher(wmiquery);
    //顯示
    ShowInfo(wmifind);
    }

    //遠程
    private void RemoteDisk()
    {
    if (cbIP.Text == "" | cbUserName.Text == "" | txtPwd.Text == "")
    {
    MessageBox.Show("請把信息補充完整!");
    return;
    }
    string ip = cbIP.Text;
    string username = cbUserName.Text;
    string password = txtPwd.Text;
    ConnectionOptions conn = new ConnectionOptions();
    conn.Username = username;
    conn.Password = password;
    conn.Timeout = new TimeSpan(1,1,1,1);//連接時間

    //ManagementScope 的服務器和命名空間。
    string path = string.Format(@"\{0} ootcimv2", ip);
    //表示管理操作的范圍(命名空間),使用指定選項初始化ManagementScope 類的、表示指定范圍路徑的新實例。
    ManagementScope scope = new ManagementScope(path, conn);
    scope.Connect();
    //查詢
    string strQuery = "select * from Win32_LogicalDisk ";
    ObjectQuery query = new ObjectQuery(strQuery);
    //查詢ManagementObjectCollection返回結果集
    ManagementObjectSearcher wmifind = new ManagementObjectSearcher(scope, query);
    ShowInfo(wmifind);
    }

    #region 顯示磁盤信息
    private void ShowInfo(ManagementObjectSearcher wmifind)
    {
    long gb = 1024 * 1024 * 1024;
    string type = "";
    string str = "";
    double freePath = 0d;
    foreach (var mobj in wmifind.Get())
    {
    type = mobj["Description"].ToString();
    //判斷是否是本機固盤
    if (type == "Local Fixed Disk")
    {
    str = " 磁盤名稱:" + mobj["Name"].ToString();
    freePath = Math.Round(Convert.ToDouble(mobj["FreeSpace"]) / gb, 1);
    str += " 可用空間:" + freePath+ "G";
    str += " 實際大小:" + Math.Round(Convert.ToDouble(mobj["Size"].ToString()) / gb, 1) + "G";
    if (freePath < 20)
    {
    str += " ----請盡快清理!";
    }
    listBox1.Items.Add(str);
    }
    }
    }
    #endregion

    private void rbtnLocal_CheckedChanged(object sender, EventArgs e)
    {
    //本地選中
    if (rbtnLocal.Checked == true)
    {
    cbIP.Enabled = false;
    cbUserName.Enabled = false;
    txtPwd.Enabled = false;
    }
    }

    private void rbtnRemote_CheckedChanged(object sender, EventArgs e)
    {
    if (rbtnRemote.Checked == true)
    {
    cbIP.Enabled = true;
    cbUserName.Enabled = true;
    txtPwd.Enabled = true;
    }
    }


    ?

    本文摘自 :https://blog.51cto.com/u

    開通會員,享受整站包年服務
    国产呦精品一区二区三区网站|久久www免费人咸|精品无码人妻一区二区|久99久热只有精品国产15|中文字幕亚洲无线码