public void Refresh() { if (managementObject != null) { managementObject.Dispose(); } managementObject = new ManagementObject(wmiManagementPath); RefreshInternal(); }
public static bool IsEMSEnabled() { bool isEMSEnabled = false; try { // {9dea862c-5cdd-4e70-acc1-f32b344d4795} is the GUID of the System BcdStore ManagementObject scopeObj = new ManagementObject(new ManagementScope(@"root\WMI"), new ManagementPath("root\\WMI:BcdObject.Id=\"{9dea862c-5cdd-4e70-acc1-f32b344d4795}\",StoreFilePath=\"\""), null); ManagementBaseObject elementObj = null; elementObj = scopeObj.GetMethodParameters("GetElement"); // Get the list of IDs from 0x24000001, which is a BCD constant: BcdBootMgrObjectList_DisplayOrder elementObj["Type"] = ((UInt32)0x24000001); ManagementBaseObject BCDObj = scopeObj.InvokeMethod("GetElement", elementObj, null); ManagementBaseObject value = ((ManagementBaseObject)(BCDObj.Properties["Element"].Value)); // Get list of Ids string[] idList = (string[])value.GetPropertyValue("Ids"); // Define the Management object used to access the WMI info from BCD store scopeObj = new ManagementObject(new ManagementScope(@"root\WMI"), new ManagementPath("root\\WMI:BcdObject.Id=\"" + idList[0] + "\",StoreFilePath=\"\""), null); elementObj = scopeObj.GetMethodParameters("GetElement"); // BcdOSLoaderBoolean_EmsEnabled (0x260000b0) // The EMS enabled setting. The element data format is BcdBooleanElement. elementObj["Type"] = ((UInt32)0x260000b0); BCDObj = scopeObj.InvokeMethod("GetElement", elementObj, null); value = ((ManagementBaseObject)(BCDObj.Properties["Element"].Value)); // try get EMS enabled setting Boolean.TryParse(value.GetPropertyValue("boolean").ToString(), out isEMSEnabled); // Dispose unmanaged objects if (scopeObj != null) { scopeObj.Dispose(); } if (elementObj != null) { elementObj.Dispose(); } if (BCDObj != null) { BCDObj.Dispose(); } if (value != null) { value.Dispose(); } } catch (Exception e) { Tracer.WriteError(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace)); } return(isEMSEnabled); }
private void CollectCPUSpeed() { ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'"); ProcessorSpeed = (uint)(Mo["CurrentClockSpeed"]); Mo.Dispose(); }
private string GetDiskId() { string diskLetter = string.Empty; //Find first drive foreach (var compDrive in DriveInfo.GetDrives()) { if (compDrive.IsReady) { diskLetter = compDrive.RootDirectory.ToString(); break; } } if (!string.IsNullOrEmpty(diskLetter) && diskLetter.EndsWith(":\\")) { //C:\ -> C diskLetter = diskLetter.Substring(0, diskLetter.Length - 2); } var disk = new ManagementObject(@"win32_logicaldisk.deviceid=""" + diskLetter + @":"""); disk.Get(); var volumeSerial = disk["VolumeSerialNumber"].ToString(); disk.Dispose(); return(volumeSerial); }
private void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { if (_process != null) { try { _process.InvokeMethod("Terminate", new object[] { 0 }); } catch { Logger.Warn("Unable to terminate remote process on [{0}].", _server); } finally { _process.Dispose(); _process = null; } } } _disposed = true; }
public static string GetMachineID() { string result; try { SelectQuery query = new SelectQuery("SELECT * FROM Win32_BaseBoard"); ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(query); ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator(); enumerator.MoveNext(); ManagementBaseObject managementBaseObject = enumerator.Current; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(managementBaseObject.GetPropertyValue("SerialNumber").ToString()); if (stringBuilder.ToString().Trim().Length < 5) { ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection instances = managementClass.GetInstances(); foreach (ManagementBaseObject managementBaseObject2 in instances) { ManagementObject managementObject = (ManagementObject)managementBaseObject2; if ((bool)managementObject["IPEnabled"]) { stringBuilder.Append(managementObject["MacAddress"].ToString()); } managementObject.Dispose(); } } result = "S7" + stringBuilder.ToString().Trim(); } catch { result = ""; } return(result); }
public static IEmulatedEthernetPortSettingData GetDefaultFromResourcePool(IResourcePool resource) { ManagementObject managementObject = (ManagementObject)null; using (ManagementObjectCollection related = ((IWMICommon)resource).Object.GetRelated("Msvm_AllocationCapabilities", "Msvm_ElementCapabilities", (string)null, (string)null, (string)null, (string)null, false, (EnumerationOptions)null)) { using (ManagementObject firstElement = related.GetFirstElement()) { foreach (ManagementObject relationship in firstElement.GetRelationships("Msvm_SettingsDefineCapabilities")) { if ((int)(ushort)relationship["ValueRole"] == 0) { managementObject = relationship; break; } relationship.Dispose(); } } } if (managementObject == null) { throw new HyperVException("Unable to find the default settings for the resource"); } string path = (string)managementObject["PartComponent"]; managementObject.Dispose(); ManagementObject instance = new ManagementObject(path); instance.Scope = ((IWMICommon)resource).Scope; instance.Get(); return((IEmulatedEthernetPortSettingData) new EmulatedEthernetPortSettingData(instance)); }
// Token: 0x060000AB RID: 171 RVA: 0x0000777C File Offset: 0x0000597C private static string DiskId(string diskLetter = "") { if (diskLetter == string.Empty) { DriveInfo[] drives = DriveInfo.GetDrives(); for (int i = 0; i < drives.Length; i++) { DriveInfo driveInfo = drives[i]; if (driveInfo.IsReady) { diskLetter = driveInfo.RootDirectory.ToString(); break; } } } if (diskLetter.EndsWith(":\\")) { diskLetter = diskLetter.Substring(0, diskLetter.Length - 2); } ManagementObject expr_7F = new ManagementObject("win32_logicaldisk.deviceid=\"" + diskLetter + ":\""); expr_7F.Get(); string result = expr_7F["VolumeSerialNumber"].ToString(); expr_7F.Dispose(); return(result); }
public static IEnumerable <string> GetDriveLetters(ManagementScope scope) { ManagementObjectCollection logicalDisks = WMIUtils.Query(scope, "select * from Win32_logicaldisk"); try { foreach (ManagementObject managementObject1 in logicalDisks) { ManagementObject managementObject = managementObject1; try { if (managementObject1["Name"] != null) { yield return((string)managementObject1["Name"]); } } finally { if (managementObject != null) { managementObject.Dispose(); } } managementObject = (ManagementObject)null; } } finally { if (logicalDisks != null) { logicalDisks.Dispose(); } } logicalDisks = (ManagementObjectCollection)null; }
private void CountQueueMessages(QSetQueueItem queueItem) { //first of all, ensure we have a node to work with QueueItemListViewItemPair itemPair = null; if (_itemPairHashTable.ContainsKey(queueItem.ID)) { itemPair = (QSetMonitorWorker.QueueItemListViewItemPair)_itemPairHashTable[queueItem.ID]; } else { //TODO create icon itemPair = new QueueItemListViewItemPair(queueItem, new ListViewItem(queueItem.Name, (int)Images.IconType.Queue)); for (int subItemCounter = 0; subItemCounter < _COLUMNS; subItemCounter++) { itemPair.ListViewItem.SubItems.Add(string.Empty); } _itemPairHashTable.Add(itemPair.QSetQueueItem.ID, itemPair); Action x = delegate { _monitorListView.Items.Add(itemPair.ListViewItem); }; _monitorListView.Invoke(x); } ManagementObject counter = null; try { counter = new ManagementObject(String.Format("Win32_PerfRawdata_MSMQ_MSMQQueue.name='{0}'", itemPair.QSetQueueItem.Name)); counter.Get(); uint outgoingMessageCount = Convert.ToUInt32(counter.GetPropertyValue("MessagesInQueue")); uint outgoingBytes = Convert.ToUInt32(counter.GetPropertyValue("BytesInQueue")); Action herewegoagain = () => { if (itemPair.ListViewItem.SubItems[(int)SubItemList.OutgoingMessageCount].Text != outgoingMessageCount.ToString()) //note: only do if necessary, to avoid flicker { itemPair.ListViewItem.SubItems[(int)SubItemList.OutgoingMessageCount].Text = outgoingMessageCount.ToString(); } if (itemPair.ListViewItem.SubItems[(int)SubItemList.OutgoingBytes].Text != outgoingBytes.ToString()) //note: only do if necessary, to avoid flicker { itemPair.ListViewItem.SubItems[(int)SubItemList.OutgoingBytes].Text = outgoingBytes.ToString(); } }; _monitorListView.Invoke(herewegoagain); } catch { //exception will occur when cannot get access to performance counters } finally { if (counter != null) { counter.Dispose(); } } }
protected override void OnAfterInstall(IDictionary savedState) { //允许服务与桌面交互 base.OnAfterInstall(savedState); ManagementObject wmiService = null; ManagementBaseObject InParam = null; try { wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'", SwitchServices.ServiceName)); InParam = wmiService.GetMethodParameters("Change"); InParam["DesktopInteract"] = true; wmiService.InvokeMethod("Change", InParam, null); } finally { if (InParam != null) { InParam.Dispose(); } if (wmiService != null) { wmiService.Dispose(); } } }
/// <summary> /// Test if the share exists. /// </summary> /// <returns>True if the share exists.</returns> public bool Exists() { // using (var shareQuery = new ManagementObjectSearcher(@"SELECT * FROM Win32_Share Where Name = '" + this.shareName + "'")) // { // return shareQuery.Get().Count > 0; // } ManagementObject shareInstance = null; try { shareInstance = new ManagementObject(@"root\cimv2:Win32_Share.Name='" + this.shareName + "'"); shareInstance.Get(); } catch (ManagementException) { return(false); } finally { if (shareInstance != null) { shareInstance.Dispose(); } } return(true); }
/// <summary> /// Deletes the share. /// </summary> public void DeleteShare() { ManagementBaseObject outParams = null; ManagementObject shareInstance = null; try { shareInstance = new ManagementObject(@"root\cimv2:Win32_Share.Name='" + this.shareName + "'"); outParams = shareInstance.InvokeMethod("Delete", null, null); if ((uint)outParams["ReturnValue"] != 0) { throw new WindowsShareException("Unable to delete share. Win32_Share.Delete Error Code: " + outParams["ReturnValue"]); } } catch (Exception ex) { throw new WindowsShareException("Unable to delete share: " + this.shareName, ex); } finally { if (shareInstance != null) { shareInstance.Dispose(); } if (outParams != null) { outParams.Dispose(); } } }
/////该函数是为了windows服务和桌面交互 private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e) { base.OnAfterInstall(e.SavedState); ManagementObject wmiService = null; ManagementBaseObject InParam = null; try { wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'", serviceInstaller1.ServiceName)); InParam = wmiService.GetMethodParameters("Change"); InParam["DesktopInteract"] = true; wmiService.InvokeMethod("Change", InParam, null); } finally { if (InParam != null) { InParam.Dispose(); } if (wmiService != null) { wmiService.Dispose(); } } }
protected override void Dispose(bool disposing) { if (disposing) { if (msTz0WmiInstance != null) { msTz0WmiInstance.Dispose(); } clevoWmiInstance.Dispose(); timerFan.Dispose(); timerUI.Stop(); timerUI.Dispose(); notifyIcon.Visible = false; notifyIcon.Dispose(); canvas.Dispose(); icon.Dispose(); iconBitmap.Dispose(); font.Dispose(); brushBg.Dispose(); brushFg.Dispose(); brushText.Dispose(); brushDrop.Dispose(); penLine.Dispose(); } base.Dispose(disposing); }
public static VMJob RequestStateChange(VM vm, int state) { ManagementScope scope = new ManagementScope(@"\\" + vm.Host.Name + @"\root\virtualization", vm.Host.HostConnectionOptions); ManagementObject vmObj = vm.Instance;//Utility.GetTargetComputer(vm.GUID, scope); ManagementBaseObject inParams = vmObj.GetMethodParameters("RequestStateChange"); inParams["RequestedState"] = state; ManagementBaseObject outParams = vmObj.InvokeMethod("RequestStateChange", inParams, null); UInt32 returnValue = (UInt32)outParams["ReturnValue"]; string jobPath = (string)outParams["Job"]; VMJob ThisJob = null; if (jobPath != null) { ThisJob = new VMJob(new ManagementObject(scope, new ManagementPath(jobPath), null)); } inParams.Dispose(); outParams.Dispose(); vmObj.Dispose(); if ((jobPath == null) && (returnValue != ReturnCode.Completed) && (returnValue != ReturnCode.Started)) { throw new VMStateChangeException(returnValue); } //JobCompleted(outParams, scope, out ErrorCode); return(ThisJob); }
public void PostRun() { if (_Item != null) { _Item.Dispose(); } }
public WMI(string path) { this.names = new StringDictionary(); this.mocs = new ArrayList(); try { ManagementClass managementClass = new ManagementClass(path); ManagementObjectCollection instances = managementClass.GetInstances(); bool flag = false; using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = instances.GetEnumerator()) { while (enumerator.MoveNext()) { ManagementObject managementObject = (ManagementObject)enumerator.Current; Hashtable hashtable = new Hashtable(); this.mocs.Add(hashtable); foreach (PropertyData current in managementObject.Properties) { hashtable.Add(current.Name, current.Value); if (!flag) { this.names.Add(current.Name, current.Name); } } flag = true; managementObject.Dispose(); } } instances.Dispose(); } catch (Exception ex) { throw new Exception(ex.Message); } }
private static string[] GetSystemInfo() { var buf = new string[5]; try { var Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'"); buf[0] = (Mo["Name"]).ToString(); buf[1] = (Mo["CurrentClockSpeed"]).ToString(); Mo.Dispose(); Mo = new ManagementObject("Win32_OperatingSystem=@"); buf[2] = (Mo["TotalVisibleMemorySize"]).ToString(); Mo.Dispose(); } catch { for (int i = 0; i < buf.Length; i++) { if (buf[i] == null) { buf[i] = "Error getting value"; } } } return(buf); }
private void Delete() { if (!this.CheckExists()) { return; } string queryString = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM MSBTS_SendHandler2 WHERE AdapterName = '{0}'", this.AdapterName); ObjectQuery query = new ObjectQuery(queryString); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query, null)) { ManagementObjectCollection objects = searcher.Get(); ManagementObject newDefault = null; try { if (objects.Count > 0) { foreach (ManagementObject obj in objects) { if (!Convert.ToBoolean(obj["IsDefault"], CultureInfo.InvariantCulture)) { newDefault = obj; break; } } foreach (ManagementObject obj in objects) { if (string.Compare(obj["HostName"].ToString(), this.HostName, StringComparison.OrdinalIgnoreCase) == 0) { this.sendHandler = obj; if (Convert.ToBoolean(this.sendHandler["IsDefault"], CultureInfo.InvariantCulture)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Changing Default Send Handler to: {0}", newDefault["HostName"])); newDefault["IsDefault"] = true; newDefault.Put(new PutOptions { Type = PutType.UpdateOnly }); this.explorer.SaveChanges(); } else { break; } } } this.sendHandler.Delete(); } } finally { if (newDefault != null) { newDefault.Dispose(); } } } }
// Updates the NicInfo struct // Uses WMI to extract information about network adapters public void UpdateNicInfo() { NicInfo n = new NicInfo(); NicList.Clear(); foreach (ManagementObject a in AdapterCollection) { if ((bool)a.GetPropertyValue("PhysicalAdapter")) { // Get info from AdapterColection n.DeviceID = (string)a.GetPropertyValue("DeviceID"); n.Name = (string)a.GetPropertyValue("NetConnectionID"); n.Description = (string)a.GetPropertyValue("Description"); n.NetEnabled = (bool)a.GetPropertyValue("NetEnabled"); // Fetch one specific adapter configuration based on DeviceID ManagementObject mo = new ManagementObject("Win32_NetworkAdapterConfiguration.Index=" + n.DeviceID); // Get IP info from that configuration n.DHCP = (bool)mo.GetPropertyValue("DHCPEnabled"); n.IpAddress = (string[])mo.GetPropertyValue("IPAddress"); n.SubnetMask = (string[])mo.GetPropertyValue("IPSubnet"); n.Gateway = (string[])mo.GetPropertyValue("DefaultIPGateway"); n.DNS = (string[])mo.GetPropertyValue("DNSServerSearchOrder"); NicList.Add(n); mo.Dispose(); } } }
// Token: 0x060000ED RID: 237 RVA: 0x0000636C File Offset: 0x0000456C private static string DiskId(string diskLetter = "") { if (diskLetter == string.Empty) { foreach (DriveInfo driveInfo in DriveInfo.GetDrives()) { if (driveInfo.IsReady) { diskLetter = driveInfo.RootDirectory.ToString(); break; } } } if (diskLetter.EndsWith(":\\")) { diskLetter = diskLetter.Substring(0, diskLetter.Length - 2); } ManagementObject managementObject = new ManagementObject("win32_logicaldisk.deviceid=\"" + diskLetter + ":\""); managementObject.Get(); string result = managementObject["VolumeSerialNumber"].ToString(); managementObject.Dispose(); return(result); }
/// <summary> /// Supports managed resources disposal /// </summary> /// <param name="zoneName"></param> private void UpdateSoaRecord(string zoneName) { // get existing SOA record in order to read serial number try { //ManagementObject obj = GetWmiObject("MicrosoftDNS_Zone", "ContainerName = '{0}'", zoneName); //ManagementObject objSoa = GetRelatedWmiObject(obj, "MicrosoftDNS_SOAType"); ManagementObject objSoa = wmi.GetWmiObject("MicrosoftDNS_SOAType", "ContainerName = '{0}'", RemoveTrailingDot(zoneName)); if (objSoa != null) { if (objSoa.Properties["OwnerName"].Value.Equals(zoneName)) { string primaryServer = (string)objSoa.Properties["PrimaryServer"].Value; string responsibleParty = (string)objSoa.Properties["ResponsibleParty"].Value; UInt32 serialNumber = (UInt32)objSoa.Properties["SerialNumber"].Value; // update record's serial number string sn = serialNumber.ToString(); string todayDate = DateTime.Now.ToString("yyyyMMdd"); if (sn.Length < 10 || !sn.StartsWith(todayDate)) { // build a new serial number sn = todayDate + "01"; serialNumber = UInt32.Parse(sn); } else { // just increment serial number serialNumber += 1; } // update SOA record using (ManagementBaseObject methodParams = objSoa.GetMethodParameters("Modify")) { methodParams["ResponsibleParty"] = responsibleParty; methodParams["PrimaryServer"] = primaryServer; methodParams["SerialNumber"] = serialNumber; methodParams["ExpireLimit"] = ExpireLimit; methodParams["MinimumTTL"] = MinimumTTL; methodParams["TTL"] = MinimumTTL; methodParams["RefreshInterval"] = RefreshInterval; methodParams["RetryDelay"] = RetryDelay; ManagementBaseObject outParams = objSoa.InvokeMethod("Modify", methodParams, null); } // objSoa.Dispose(); } } } catch (Exception ex) { Log.WriteError(ex); } }
public static string GetMACAddress() { ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); string MACAddress = string.Empty; try { ManagementObjectCollection.ManagementObjectEnumerator enumerator = moc.GetEnumerator(); while (enumerator.MoveNext()) { ManagementObject mo = (ManagementObject)enumerator.Current; if (Operators.CompareString(MACAddress, string.Empty, false) == 0 && Conversions.ToBoolean(mo["IPEnabled"])) { MACAddress = mo["MacAddress"].ToString(); } mo.Dispose(); } } finally { ManagementObjectCollection.ManagementObjectEnumerator enumerator; if (enumerator != null) { ((IDisposable)enumerator).Dispose(); } } MACAddress = MACAddress.Replace(":", ""); return(MACAddress); }
private static string DiskId(String diskLetter) { //Find first drive if (diskLetter == "") { foreach (DriveInfo compDrive in DriveInfo.GetDrives()) { if (compDrive.IsReady) { diskLetter = compDrive.RootDirectory.ToString(); break; } } } if (diskLetter.EndsWith(":\\")) { //C:\ -> C diskLetter = diskLetter.Substring(0, diskLetter.Length - 2); } ManagementObject disk = new ManagementObject(@"win32_logicaldisk.deviceid=""" + diskLetter + @":"""); disk.Get(); string volumeSerial = disk["VolumeSerialNumber"].ToString(); disk.Dispose(); return(volumeSerial); }
public Dictionary <string, string> getInfo(string vmName) { Dictionary <string, string> infos = new Dictionary <string, string>(); string[] InfoNode = { "0", "4", "101", "103", "105", "106", "109", "112" }; //VM getSummaryInfo = new VM(); ManagementObject virtualSystemSetting = GetVirtualSystemSetting(vmName); ManagementObject[] settings = new ManagementObject[1]; settings[0] = virtualSystemSetting; UInt32[] requestedInfo = new UInt32[InfoNode.Length - 1]; for (int i = 1; i < InfoNode.Length; ++i) { requestedInfo[i - 1] = UInt32.Parse(InfoNode[i].ToString()); } if (settings[0] != null) { infos = GetSummaryInformation(settings, requestedInfo); } if (virtualSystemSetting != null) { virtualSystemSetting.Dispose(); } return(infos); }
/// <summary> /// Resets NTFS permissions by username /// </summary> /// <param name="path"></param> internal static void ResetNtfsPermissions(string path) { // remove trailing slash if any if (path.EndsWith("\\")) { path = path.Substring(0, path.Length - 1); } ManagementObject logicalFileSecuritySetting = wmi.GetObject(String.Format( "Win32_LogicalFileSecuritySetting.Path='{0}'", path)); // get security descriptor ManagementBaseObject outParams = logicalFileSecuritySetting.InvokeMethod("GetSecurityDescriptor", null, null); ManagementObject newDescriptor = wmi.GetClass("Win32_SecurityDescriptor").CreateInstance(); newDescriptor.Properties["DACL"].Value = new ManagementBaseObject[] {}; newDescriptor.Properties["ControlFlags"].Value = 33796; // inherit permissions ManagementBaseObject inParams = null; inParams = logicalFileSecuritySetting.GetMethodParameters("SetSecurityDescriptor"); inParams["Descriptor"] = newDescriptor; outParams = logicalFileSecuritySetting.InvokeMethod("SetSecurityDescriptor", inParams, null); // This line is where I get a result back of 1307 in ASP.NET uint result = (uint)(outParams.Properties["ReturnValue"].Value); logicalFileSecuritySetting.Dispose(); }
private static string GetVolumeSerial(char driveLetter) { string volumeSerial; try { using (var disk = new ManagementObject($@"win32_logicaldisk.deviceid=""{char.ToLower(driveLetter)}:""")) { disk.Get(); volumeSerial = disk["VolumeSerialNumber"].ToString(); disk.Dispose(); } } catch (Exception ex) { throw new InvalidOperationException($"Not possible to find disk {driveLetter}:.", ex); } if (string.IsNullOrEmpty(volumeSerial)) { throw new InvalidOperationException($"Volume Serial Number for drive '{driveLetter}' is null or empty."); } return(volumeSerial); }
public void Dispose() { if (adapter != null) { adapter.Dispose(); } }
public static UsbDriveInfo LoadUsbFromDriveLetter(char driveLetter) { const int maxAttempts = 5; try { if (char.IsLetter(driveLetter)) { for (int attempts = 0; attempts < maxAttempts; ++attempts) { try { ManagementObject logicalObj = GetLogicalObjectFromDriveLetter(driveLetter); logicalObj.Get(); ManagementObject diskObj = GetDiskObjectFromLogical(logicalObj); string volumeName = logicalObj["VolumeName"].ToString(); object serialNumberObject = logicalObj["VolumeSerialNumber"]; string modelName = diskObj["Model"].ToString(); object pnpDeviceId = diskObj["PNPDeviceID"]; string uniqueId = FormatDriveUniqueID(serialNumberObject != null ? serialNumberObject.ToString() : "", pnpDeviceId != null ? pnpDeviceId.ToString() : ""); UsbDriveInfo driveInfo = UsbDriveList.Instance.GetUsbInfoByUniqueId(uniqueId); if (driveInfo == null) { driveInfo = UsbDriveList.Instance.CreateEmptyUsbInfo(modelName, volumeName, uniqueId); } string sizeString = logicalObj["Size"].ToString(); System.UInt64 sizeBytes = 0; System.UInt64.TryParse(sizeString, out sizeBytes); driveInfo.__MarkActive(driveLetter, sizeBytes); diskObj.Dispose(); logicalObj.Dispose(); return(driveInfo); } catch (System.Exception) { // failed, try again until maxAttempts //UsbDriveList.__LogError( null, "LoadUsbFromDriveLetter attempt failed : " + (attempts + 1) + "/" + maxAttempts, e ); System.Threading.Thread.Sleep(200); } } } else { throw new Exception("Drive letter is not valid " + driveLetter.ToString()); } } catch (System.Exception e) { UsbDriveList.__LogError(null, "UsbPrivate.LoadUsbFromDriveLetter", e); return(null); } return(null); }