程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 獲取磁盤空間大小的方法,

C# 獲取磁盤空間大小的方法,

編輯:C#入門知識

C# 獲取磁盤空間大小的方法,


方法一:利用System.IO.DriveInfo.GetDrives方法來獲取

///   
        /// 獲取指定驅動器的空間總大小(單位為B) 
        ///   
        ///  只需輸入代表驅動器的字母即可 (大寫) 
        ///    
        public static long GetHardDiskSpace(string str_HardDiskName) 
        { 
            long totalSize= new long(); 
            str_HardDiskName=str_HardDiskName +":\\"; 
            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives(); 
            foreach (System.IO.DriveInfo drive in drives) 
            { 
                if (drive.Name == str_HardDiskName) 
                {
                    totalSize = drive.TotalSize / (1024 * 1024 * 1024); 
                } 
            } 
            return totalSize; 
        }

        ///   
        /// 獲取指定驅動器的剩余空間總大小(單位為B) 
        ///   
        ///  只需輸入代表驅動器的字母即可  
        ///    
        public static long GetHardDiskFreeSpace(string str_HardDiskName) 
        { 
            long freeSpace = new long(); 
            str_HardDiskName = str_HardDiskName + ":\\"; 
            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives(); 
            foreach (System.IO.DriveInfo drive in drives) 
            { 
                if (drive.Name == str_HardDiskName) 
                {
                    freeSpace = drive.TotalFreeSpace / (1024 * 1024 * 1024); 
                } 
            } 
            return freeSpace; 
        }

方法二:利用ManagementClass("Win32_LogicalDisk")來獲取

List<Dictionary<string, string>> diskInfoDic = new List<Dictionary<string, string>>();
ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
			ManagementObjectCollection disks = diskClass.GetInstances();
			foreach(ManagementObject disk in disks)
			{
				Dictionary<string, string> diskInfo = new Dictionary<string, string>();
				try
				{
					// 磁盤名稱
					diskInfo["Name"] =disk["Name"].ToString();
					// 磁盤描述
					diskInfo["Description"]=disk["Description"].ToString();
					// 磁盤總容量,可用空間,已用空間
					if (System.Convert.ToInt64(disk["Size"]) > 0)
					{
						long totalSpace = System.Convert.ToInt64(disk["Size"]) / MB;
						long freeSpace = System.Convert.ToInt64(disk["FreeSpace"]) / MB;
						long usedSpace = totalSpace - freeSpace;
                        			diskInfo["totalSpace"]=totalSpace.ToString();
						diskInfo["usedSpace"]=usedSpace.ToString();
						diskInfo["freeSpace"]=freeSpace.ToString();
					}
					diskInfoDic.Add(diskInfo);
				}
				catch(Exception ex)
				{
					Throw ex;
				}
			}

更多IT相關資訊與技術文章,歡迎光臨我的個人網站:http://www.zuowenjun.cn/

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved