private void SaveSettings(UsbDisk[] disks = null, string drive = "") { Settings.Default.APP_DISK_IDS = UsbDisk.serialize(disks); Settings.Default.APP_MAP_DRIVE = drive; Settings.Default.Save(); usbDrivesToMount = (disks != null) ? disks.Select(d => d.SerialNumber).ToArray() : new string[] { }; }
private void comboBoxDisk_SelectedIndexChanged(object sender, EventArgs e) { UdObj = (UsbDisk)comboBoxDisk.SelectedItem; if (UdObj != null) { diskRootPath = UdObj.Volume.Substring(0, 1) + ":\\"; } }
private void LoadConfiguration() { UsbDisk[] disks = UsbDisk.deserializeAll(Settings.Default.APP_DISK_IDS); disksList.Items.Clear(); disksList.Items.AddRange(disks); mappedDrive = !String.IsNullOrEmpty(Settings.Default.APP_MAP_DRIVE) ? Settings.Default.APP_MAP_DRIVE[0] : DEFAULT_DRIVE; usbDrivesToMount = disks.Select(d => d.SerialNumber).ToArray(); refreshAvailableDisks(); }
private void mapDrive(char mountDrive, UsbDisk disk, bool unmapfirst = false) { if (unmapfirst) { Subst.UnmapDrive(mountDrive); // Unmount the bad one } string mountedFolder = disk.Name + @"\"; Subst.MapDrive(mountDrive, mountedFolder); // mount the new one logText(string.Format("Virtual drive '{0}:' mounted to disk '{1}' ({2}/{3}) ", mountDrive, disk.Name, disk.Volume, disk.SerialNumber)); }
private IEnumerable <UsbDisk> GetUsbDisks() { Thread.Sleep(50); var usbDisks = new List <UsbDisk>(); using (Device device = Device.Get(this.PnpDeviceID)) { // get children devices foreach (string childDeviceId in device.ChildrenPnpDeviceIds) { // get the drive object that correspond to this id (escape the id) var driveSearcher = new ManagementObjectSearcher("SELECT DeviceID FROM Win32_DiskDrive WHERE PNPDeviceID='" + childDeviceId.Replace(@"\", @"\\") + "'"); using (var drives = driveSearcher.Get()) { foreach (var drive in drives) { var partitionSearcher = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass=Win32_DiskDriveToDiskPartition"); using (var partitions = partitionSearcher.Get()) { // associate physical disks with partitions foreach (var partition in partitions) { var diskSearcher = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass=Win32_LogicalDiskToPartition"); using (var disks = diskSearcher.Get()) { // associate partitions with logical disks (drive letter volumes) foreach (var disk in disks) { var usbDisk = new UsbDisk(); usbDisk.VolumeName = disk["VolumeName"].ToStringOrEmpty(); usbDisk.DriveLetter = disk["DeviceID"].ToStringOrEmpty(); usbDisks.Add(usbDisk); } } diskSearcher.Dispose(); } } partitionSearcher.Dispose(); } } driveSearcher.Dispose(); } } return(usbDisks); }
private void OnMenuItemClick(object sender, EventArgs e) { UsbDisk disk = (UsbDisk)((MenuItem)sender).Tag; bool duplicate = disksList.Items.Cast <UsbDisk>().Any(d => d.SerialNumber == disk.SerialNumber); if (!duplicate) { disksList.Items.Add(disk); SaveConfig(true); } else { MessageBox.Show(string.Format("Disk {0}/{1} has already been added!", disk.Volume, disk.SerialNumber)); } }
public void CollectionTest() { UsbDiskCollection disks = new UsbDiskCollection(); Assert.IsFalse(disks.Contains("foo")); UsbDisk disk = new UsbDisk("foo"); disks.Add(disk); Assert.IsTrue(disks.Contains(disk)); Assert.IsTrue(disks.Contains("foo")); Assert.IsFalse(disks.Contains("missing")); disks.Remove("foo"); Assert.AreEqual(0, disks.Count); Assert.IsFalse(disks.Contains("foo")); }
private void SignalDeviceChange(UsbStateChange state, DEV_BROADCAST_VOLUME volume) { string name = ToUnitName(volume.dbcv_unitmask); if (StateChanged != null) { UsbDisk disk = new UsbDisk(name); StateChanged(new UsbStateChangedEventArgs(state, disk)); } }
/// <summary> /// Populate the missing properties of the given disk before sending to listeners /// </summary> /// <param name="disk"></param> private void GetDiskInformation(UsbDisk disk) { ManagementObject partition = new ManagementObjectSearcher(String.Format( "associators of {{Win32_LogicalDisk.DeviceID='{0}'}} where AssocClass = Win32_LogicalDiskToPartition", disk.Name)).First(); if (partition != null) { ManagementObject drive = new ManagementObjectSearcher(String.Format( "associators of {{Win32_DiskPartition.DeviceID='{0}'}} where resultClass = Win32_DiskDrive", partition["DeviceID"])).First(); if (drive != null) { disk.Model = drive["Model"].ToString(); } ManagementObject volume = new ManagementObjectSearcher(String.Format( "select FreeSpace, Size, VolumeName from Win32_LogicalDisk where Name='{0}'", disk.Name)).First(); if (volume != null) { disk.Volume = volume["VolumeName"].ToString(); disk.FreeSpace = (ulong)volume["FreeSpace"]; disk.Size = (ulong)volume["Size"]; } } }
//======================================================================================== // Methods //======================================================================================== /// <summary> /// Gets a collection of all available USB disk drives currently mounted. /// </summary> /// <returns> /// A UsbDiskCollection containing the USB disk drives. /// </returns> public UsbDiskCollection GetAvailableDisks() { UsbDiskCollection disks = new UsbDiskCollection(); // browse all USB WMI physical disks foreach (ManagementObject drive in new ManagementObjectSearcher( "select DeviceID, Model from Win32_DiskDrive where InterfaceType='USB'").Get()) { // associate physical disks with partitions ManagementObject partition = new ManagementObjectSearcher(String.Format( "associators of {{Win32_DiskDrive.DeviceID='{0}'}} where AssocClass = Win32_DiskDriveToDiskPartition", drive["DeviceID"])).First(); if (partition != null) { // associate partitions with logical disks (drive letter volumes) ManagementObject logical = new ManagementObjectSearcher(String.Format( "associators of {{Win32_DiskPartition.DeviceID='{0}'}} where AssocClass = Win32_LogicalDiskToPartition", partition["DeviceID"])).First(); if (logical != null) { // finally find the logical disk entry to determine the volume name ManagementObject volume = new ManagementObjectSearcher(String.Format( "select FreeSpace, Size, VolumeName from Win32_LogicalDisk where Name='{0}'", logical["Name"])).First(); UsbDisk disk = new UsbDisk(logical["Name"].ToString()); disk.Model = drive["Model"].ToString(); disk.Volume = volume["VolumeName"].ToString(); disk.FreeSpace = (ulong)volume["FreeSpace"]; disk.Size = (ulong)volume["Size"]; disks.Add(disk); } } } return disks; }
private void updateVirtualDriveMapping() { try { allowStateChangeEvent = false; bool isDriveMapped = false; int driveMappedIndex = -1; string driveStatusText = String.Empty; char virtualDrive = mappedDrive; // Copy localy since comes from combobox bool isVirtualDriveMapped = Subst.IsMappedDrive(virtualDrive); if (!isVirtualDriveMapped && Subst.IsDriveMounted(virtualDrive)) { // Husten, when have a problem, we cannot mount anything to this permanent drive logText("WARNING : Target mapping drive '" + virtualDrive + "' is a permanent physical drive!"); SetNotifyInfo(isDriveMapped, string.Format("Invalid target drive '{0}:'", virtualDrive)); return; } IList <UsbDisk> usbDisks = disks.ContainsVolumeSerials(usbDrivesToMount); if (usbDisks.Count > 0) // A backup disk is available to be mounted { UsbDisk diskToMount = usbDisks.First(); driveMappedIndex = Array.IndexOf(usbDrivesToMount, diskToMount.SerialNumber) + 1; isDriveMapped = true; if (isVirtualDriveMapped) { if (Subst.IsDriveMounted(virtualDrive)) { // A drive is mapped and mounted, is it the good one ? string mountedVolumeSN = Subst.getDriveSerialNumber(virtualDrive); if (diskToMount.SerialNumber != mountedVolumeSN) { mapDrive(virtualDrive, diskToMount, true); } else { // The mapped drive is already the good one, so should be fine logText(string.Format("Virtual drive '{0}:' already set and mounted to disk '{1}' ({2}/{3}) ", virtualDrive, diskToMount.Name, diskToMount.Volume, diskToMount.SerialNumber)); } } else // mapped, but not connected .... // probably mapped to the wrong one { mapDrive(virtualDrive, diskToMount, true); } } else // nothing mapped, so add the mapping { mapDrive(virtualDrive, diskToMount); } checkMountedDrive(virtualDrive); driveStatusText = string.Format("{0}/{1} {2} mapped to drive {3}:", diskToMount.Volume, driveMappedIndex, diskToMount.Name, virtualDrive); } else // cleanup mounted disk { if (isVirtualDriveMapped) { logText(string.Format("Virtual drive '{0}:' removed since no disk available", virtualDrive)); Subst.UnmapDrive(virtualDrive); } driveStatusText = string.Format("No USB disk on {0} mapped to drive {1}:", usbDrivesToMount.Count(), virtualDrive); } SetNotifyInfo(isDriveMapped, driveStatusText); previousMappedDrive = virtualDrive; } finally { allowStateChangeEvent = true; } }
public void GetSerFlashDisk(string licencedevid) { flgFlash = 0; string diskName = string.Empty; string testser = string.Empty; var numint = string.Empty; StringBuilder volumename = new StringBuilder(256); deviceIDflash = string.Empty; try { foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType='USB'").Get()) { foreach (System.Management.ManagementObject partition in new System.Management.ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get()) { foreach (System.Management.ManagementObject disk in new System.Management.ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get()) { diskName = disk["Name"].ToString().Trim(); testser = disk["VolumeSerialNumber"].ToString().Trim(); numint = Convert.ToInt64(testser, 16).ToString(); if (partition != null) { // associate partitions with logical disks (drive letter volumes) ManagementObject logical = new ManagementObjectSearcher(String.Format( "associators of {{Win32_DiskPartition.DeviceID='{0}'}} where AssocClass = Win32_LogicalDiskToPartition", partition["DeviceID"])).First(); if (logical != null) { List <string> list = new List <string>(); ManagementObject volume = new ManagementObjectSearcher(String.Format( "select FreeSpace, Size from Win32_LogicalDisk where Name='{0}'", logical["Name"])).First(); UsbDisk diskn = new UsbDisk(logical["Name"].ToString()); string pnpdeviceid = parseSerialFromDeviceID(drive["PNPDeviceID"].ToString().Trim()); var conpnp = pnpdeviceid.Substring(0, 5); var conpnpn = converttoascii(conpnp); var pnpdevidint = Convert.ToUInt64(conpnpn, 16).ToString(); list.Add(pnpdevidint.Substring(0, 4)); diskn.Size = (ulong)volume["Size"]; string size = diskn.ToString(); size = volume["Size"].ToString(); list.Add(size.Substring(0, 4)); list.Add(numint.Substring(0, 7)); string str = "f"; string flashser = Encrypt(str, true); list.Add(flashser); StringBuilder builder = new StringBuilder(); foreach (string cat in list) { builder.Append(cat).Append(""); } string result = builder.ToString(); deviceIDflash = result; if (licencedevid == deviceIDflash) { flgFlash = 1; flgFlashDrive = diskName; return; } } } } } } } catch (Exception ex) { error = ex.ToString(); } }
/// <summary> /// Initialize a new instance with the specified state and disk. /// </summary> /// <param name="state">The state change code.</param> /// <param name="disk">The USB disk description.</param> public UsbStateChangedEventArgs(UsbStateChange state, UsbDisk disk) { this.State = state; this.Disk = disk; }