public DriveSelectViewModel() { mode = DriveSelectMode.Individual; selectedDrives = new ObservableCollection <DriveViewModel>(); folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); validSelection = false; driveComparer = new DriveComparer(); icons = null; drives = new DriveCollection(this); selectedDrives.CollectionChanged += OnSelectionChanged; }
public static DriveCollection GetSmartInformation() { DriveCollection drives = new DriveCollection(); try { // TODO: 2017-12-19 - Refactor regions into separate methods. foreach (var device in new ManagementObjectSearcher(@"SELECT * FROM Win32_DiskDrive").Get()) { #region Drive Info Drive drive = new Drive { DeviceID = device.GetPropertyValue("DeviceID").ToString(), PnpDeviceID = device.GetPropertyValue("PNPDeviceID").ToString(), Model = device["Model"]?.ToString().Trim(), Type = device["InterfaceType"]?.ToString().Trim(), Serial = device["SerialNumber"]?.ToString().Trim() }; #endregion #region Get drive letters foreach (var partition in new ManagementObjectSearcher( "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + device.Properties["DeviceID"].Value + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get()) { foreach (var disk in new ManagementObjectSearcher( "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get()) { drive.DriveLetters.Add(disk["Name"].ToString()); } } #endregion #region Overall Smart Status ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\WMI"); ObjectQuery query = new ObjectQuery(@"SELECT * FROM MSStorageDriver_FailurePredictStatus Where InstanceName like ""%" + drive.PnpDeviceID.Replace("\\", "\\\\") + @"%"""); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection) { drive.IsOK = (bool)m.Properties["PredictFailure"].Value == false; } #endregion #region Smart Registers drive.SmartAttributes.AddRange(Helper.GetSmartRegisters(Resource.SmartAttributes)); searcher.Query = new ObjectQuery(@"Select * from MSStorageDriver_FailurePredictData Where InstanceName like ""%" + drive.PnpDeviceID.Replace("\\", "\\\\") + @"%"""); foreach (ManagementObject data in searcher.Get()) { Byte[] bytes = (Byte[])data.Properties["VendorSpecific"].Value; for (int i = 0; i < 42; ++i) { try { int id = bytes[i * 12 + 2]; int flags = bytes[i * 12 + 4]; // least significant status byte, +3 most significant byte, but not used so ignored. //bool advisory = (flags & 0x1) == 0x0; bool failureImminent = (flags & 0x1) == 0x1; //bool onlineDataCollection = (flags & 0x2) == 0x2; int value = bytes[i * 12 + 5]; int worst = bytes[i * 12 + 6]; int vendordata = BitConverter.ToInt32(bytes, i * 12 + 7); if (id == 0) { continue; } var attr = drive.SmartAttributes.GetAttribute(id); attr.Current = value; attr.Worst = worst; attr.Data = vendordata; attr.IsOK = failureImminent == false; } catch (Exception ex) { // given key does not exist in attribute collection (attribute not in the dictionary of attributes) Debug.WriteLine(ex.Message); } } } searcher.Query = new ObjectQuery(@"Select * from MSStorageDriver_FailurePredictThresholds Where InstanceName like ""%" + drive.PnpDeviceID.Replace("\\", "\\\\") + @"%"""); foreach (ManagementObject data in searcher.Get()) { Byte[] bytes = (Byte[])data.Properties["VendorSpecific"].Value; for (int i = 0; i < 42; ++i) { try { int id = bytes[i * 12 + 2]; int thresh = bytes[i * 12 + 3]; if (id == 0) { continue; } var attr = drive.SmartAttributes.GetAttribute(id); attr.Threshold = thresh; // Debug // Console.WriteLine("{0}\t {1}\t {2}\t {3}\t " + attr.Data + " " + ((attr.IsOK) ? "OK" : ""), attr.Name, attr.Current, attr.Worst, attr.Threshold); } catch (Exception ex) { // given key does not exist in attribute collection (attribute not in the dictionary of attributes) Debug.WriteLine(ex.Message); } } } #endregion drives.Add(drive); } } catch (Exception ex) { throw new Exception("Error retrieving Smart data for one or more drives. " + ex.Message); } return(drives); }
private void run() { DataRow row = dt.NewRow(); int step = 0; DriveInfo[] drives = DriveInfo.GetDrives(); DriveCollection SmartDrives = null; try { SmartDrives = Simplified.IO.Smart.GetDrives(); } catch { } int _stephdd = 0; int total_step = drives.Count(); //_form.hdd_grid.Rows.Clear(); //_form.UpdateUI_DataGridGrid(_form.hdd_grid, "clear", "", "", -1); foreach (var drive in drives) { row = dt.NewRow(); _form.setStatusBar("硬碟資訊載入中...", Convert.ToInt32((Convert.ToDouble(_stephdd) / Convert.ToDouble(total_step)) * 100.0)); _stephdd++; //There are more attributes you can use. //Check the MSDN link for a complete example. //Console.WriteLine(drive.Name); if (!drive.IsReady) { continue; } string driverName = drive.Name; driverName = driverName.Replace("\\", ""); DriveType driverType = drive.DriveType; long freeSpace = drive.TotalFreeSpace; long totalSize = drive.TotalSize; long usageSize = totalSize - freeSpace; //_form.hdd_grid.Rows.Add(); //_form.UpdateUI_DataGridGrid(_form.hdd_grid, "add", "", "", -1); //int lastId = _form.hdd_grid.Rows.Count - 1; //_form.hdd_grid.Rows[lastId].Cells["hddID"].Value = driverName; row["hddID"] = driverName; //_form.hdd_grid.Rows[lastId].Cells["hddType"].Value = driverType.ToString(); row["hddType"] = driverType.ToString(); //_form.hdd_grid.Rows[lastId].Cells["hddFormatType"].Value = drive.DriveFormat; row["hddFormatType"] = drive.DriveFormat; //_form.hdd_grid.Rows[lastId].Cells["hddTotalSpace"].Value = totalSize; row["hddTotalSpace"] = totalSize; //_form.hdd_grid.Rows[lastId].Cells["hddTotalSpaceDisplay"].Value = _form.my.size_hum_read(totalSize); //_form.UpdateUI_DataGridGrid(_form.hdd_grid, "set_cell", "hddTotalSpaceDisplay", _form.my.size_hum_read(totalSize), lastId); row["hddTotalSpaceDisplay"] = _form.my.size_hum_read(totalSize); //_form.hdd_grid.Rows[lastId].Cells["hddUsageSpace"].Value = usageSize; row["hddUsageSpace"] = usageSize; //_form.hdd_grid.Rows[lastId].Cells["hddUsageSpaceDisplay"].Value = _form.my.size_hum_read(usageSize); row["hddUsageSpaceDisplay"] = _form.my.size_hum_read(usageSize); //_form.hdd_grid.Rows[lastId].Cells["hddFreeSpace"].Value = freeSpace; row["hddFreeSpace"] = freeSpace; //_form.hdd_grid.Rows[lastId].Cells["hddFreeSpaceDisplay"].Value = _form.my.size_hum_read(freeSpace); //_form.UpdateUI_DataGridGrid(_form.hdd_grid, "set_cell", "hddFreeSpaceDisplay", _form.my.size_hum_read(freeSpace), lastId); row["hddFreeSpaceDisplay"] = _form.my.size_hum_read(freeSpace); double percent = (Convert.ToDouble(usageSize) / Convert.ToDouble(totalSize)) * 100.0; //_form.hdd_grid.Rows[lastId].Cells["hddUsagePercent"].Value = string.Format("{0:0.00}", percent) + " %"; row["hddUsagePercent"] = string.Format("{0:0.00}", percent) + " %"; //_form.hdd_grid.Rows[lastId].Cells["hddUsagePercent"].Style.Alignment = DataGridViewContentAlignment.MiddleCenter; if (percent < 60) { //_form.hdd_grid.Rows[lastId].Cells["hddUsagePercent"].Style.ForeColor = Color.Green; } else if (percent >= 60 && percent < 85) { //_form.hdd_grid.Rows[lastId].Cells["hddUsagePercent"].Style.ForeColor = Color.Orange; } else { //剩很少空間 //_form.hdd_grid.Rows[lastId].Cells["hddUsagePercent"].Style.ForeColor = Color.Red; //_form.hdd_grid.Rows[lastId].Cells["hddUsagePercent"].Style.Font = new Font(_form.hdd_grid.Columns["hddUsagePercent"].DefaultCellStyle.Font, FontStyle.Bold); //_form.UpdateUI_DataGridGrid(_form.hdd_grid, "set_font", "hddUsagePercent", new Font(_form.hdd_grid.Columns["hddUsagePercent"].DefaultCellStyle.Font, FontStyle.Bold), lastId); } //接下來是跑 smart try { foreach (var SmartDrive in SmartDrives) { if (SmartDrive.DriveLetters.Count == 0) { continue; } if (!_form.my.in_array(driverName, SmartDrive.DriveLetters)) { //同名才處理 continue; } /*if (SmartDrive.DriveLetters[0] != driverName) * { * continue; * } */ //型號 //_form.hdd_grid.Rows[lastId].Cells["hddModel"].Value = SmartDrive.Model; //_form.UpdateUI_DataGridGrid(_form.hdd_grid, "set_cell", "hddModel", SmartDrive.Model, lastId); row["hddModel"] = SmartDrive.Model; //Console.WriteLine(_form.my.json_encode(SmartDrive)); //查看有哪些屬性 //_form.logError(_form.my.json_encode(SmartDrive)); //Console.WriteLine(SmartDrive.DriveLetters[0] + "," + driverName); foreach (var p in SmartDrive.SmartAttributes) { //Console.WriteLine(p.Name); switch (p.Name) { case "Temperature": //溫度 if (p.Register == 194) { string t = p.Data.ToString(); if (p.Data > 300) { //10進制轉16進制,取最後二碼,再還原10進制 //From : https://www.techiedelight.com/conversion-between-integer-and-hexadecimal-csharp/ string hex_str = p.Data.ToString("X"); hex_str = hex_str.Substring(hex_str.Length - 2, 2); t = Int32.Parse(hex_str, System.Globalization.NumberStyles.HexNumber).ToString(); } //_form.hdd_grid.Rows[lastId].Cells["hddTemperature"].Value = t.ToString(); row["hddTemperature"] = t.ToString(); } break; case "Reallocated sector count": //壞軌數 //_form.hdd_grid.Rows[lastId].Cells["hddBadSectors"].Value = p.Data; row["hddBadSectors"] = p.Data; break; case "Power-on hours count": //開機時數 //_form.hdd_grid.Rows[lastId].Cells["hddUsageHour"].Value = p.Data; row["hddUsageHour"] = p.Data; break; case "Power cycle count": //開關機次數 //_form.hdd_grid.Rows[lastId].Cells["hddOnOffTimes"].Value = p.Data; row["hddOnOffTimes"] = p.Data; break; } } } } catch { } dt.Rows.Add(row); } // Drives _form.updateDGVUI(_form.hdd_grid, dt); _form.setStatusBar("就緒", 0); is_running = false; }