PhysicalDiskHelper.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /* Copyright (C) 2014-2020 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System.Collections.Generic;
  8. using System.IO;
  9. namespace DiskAccessLibrary.Win32
  10. {
  11. public class PhysicalDiskHelper
  12. {
  13. public static List<PhysicalDisk> GetPhysicalDisks()
  14. {
  15. List<PhysicalDisk> result = new List<PhysicalDisk>();
  16. List<int> diskIndexList = PhysicalDiskControl.GetPhysicalDiskIndexList();
  17. foreach (int diskIndex in diskIndexList)
  18. {
  19. PhysicalDisk disk;
  20. try
  21. {
  22. disk = new PhysicalDisk(diskIndex); // will throw an exception if disk is not valid
  23. }
  24. catch (DriveNotFoundException)
  25. {
  26. // The disk must have been removed from the system
  27. continue;
  28. }
  29. catch (DeviceNotReadyException)
  30. {
  31. continue;
  32. }
  33. catch (SharingViolationException) // skip this disk, it's probably being used
  34. {
  35. continue;
  36. }
  37. catch (InvalidDataException)
  38. {
  39. // e.g. When using Dataram RAMDisk v4.4.0 RC36
  40. continue;
  41. }
  42. result.Add(disk);
  43. }
  44. return result;
  45. }
  46. public static bool LockAllOrNone(List<PhysicalDisk> disks)
  47. {
  48. bool success = true;
  49. int lockIndex;
  50. for(lockIndex = 0; lockIndex < disks.Count; lockIndex++)
  51. {
  52. success = disks[lockIndex].ExclusiveLock();
  53. if (!success)
  54. {
  55. break;
  56. }
  57. }
  58. // release the disks that were locked
  59. if (!success)
  60. {
  61. for (int index = 0; index < lockIndex; index++)
  62. {
  63. disks[index].ReleaseLock();
  64. }
  65. }
  66. return success;
  67. }
  68. /// <summary>
  69. /// Will not persist across reboots
  70. /// </summary>
  71. public static bool OfflineAllOrNone(List<PhysicalDisk> disks)
  72. {
  73. bool success = true;
  74. int offlineIndex;
  75. for (offlineIndex = 0; offlineIndex < disks.Count; offlineIndex++)
  76. {
  77. success = disks[offlineIndex].SetOnlineStatus(false, false);
  78. if (!success)
  79. {
  80. break;
  81. }
  82. }
  83. // online the disks that were offlined
  84. if (!success)
  85. {
  86. for (int index = 0; index < offlineIndex; index++)
  87. {
  88. disks[index].SetOnlineStatus(true, false);
  89. }
  90. }
  91. return success;
  92. }
  93. }
  94. }