C# 获取电脑硬盘剩余空间
获取本地硬盘的所有剩余空间:
主要应用到System.IO类库的:Driveinfo、Directory,将model转换成json需要用到Newtonsoft.Json.JsonConvert.SerializeObject方法
主要方法:
public DiskList DisklistCon(string disk) { DiskList dl = new DiskList(); string[] diskcon = null; dl.msgList = new List<DiskCon>(); dl.msg = "成功!"; if (!string.IsNullOrEmpty(disk)) { DriveInfo di = new DriveInfo(disk); DiskCon dk = new DiskCon(); dk.DiskName = disk; dk.DiskLength = di.AvailableFreeSpace; dl.msgList.Add(dk); dl.count = 1; } else { try { diskcon = Directory.GetLogicalDrives(); } catch { } if (diskcon != null && diskcon.Count() > 0) { foreach (string diskname in diskcon) { DriveInfo di = new DriveInfo(diskname); DiskCon dk = new DiskCon(); dk.DiskName = diskname; dk.DiskLength = di.AvailableFreeSpace; dl.msgList.Add(dk); } dl.count = diskcon.Count(); } } return dl; }
Model方法:
public class DiskList { public string msg { get; set; } public List<DiskCon> msgList { get; set; } public int count { get; set; } } public class DiskCon { public string DiskName { get; set; } public long DiskLength { get; set; } public string DiskGb { get { return (DiskLength * 1.0 / 1024 / 1024 / 1024).ToString("0.00GB"); } } }