PhysicalDiskHelper.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /* Copyright (C) 2014 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;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Text;
  11. using Utilities;
  12. namespace DiskAccessLibrary
  13. {
  14. public class PhysicalDiskHelper
  15. {
  16. public static List<PhysicalDisk> GetPhysicalDisks()
  17. {
  18. List<PhysicalDisk> result = new List<PhysicalDisk>();
  19. List<int> diskIndexList = PhysicalDiskUtils.GetPhysicalDiskIndexList();
  20. foreach (int diskIndex in diskIndexList)
  21. {
  22. PhysicalDisk disk;
  23. try
  24. {
  25. disk = new PhysicalDisk(diskIndex); // will throw an exception if disk is not valid
  26. }
  27. catch (DriveNotFoundException)
  28. {
  29. // The disk must have been removed from the system
  30. continue;
  31. }
  32. catch (DeviceNotReadyException)
  33. {
  34. continue;
  35. }
  36. catch (SharingViolationException) // skip this disk, it's probably being used
  37. {
  38. continue;
  39. }
  40. result.Add(disk);
  41. }
  42. return result;
  43. }
  44. public static bool LockAllOrNone(List<PhysicalDisk> disks)
  45. {
  46. bool success = true;
  47. int lockIndex;
  48. for(lockIndex = 0; lockIndex < disks.Count; lockIndex++)
  49. {
  50. success = disks[lockIndex].ExclusiveLock();
  51. if (!success)
  52. {
  53. break;
  54. }
  55. }
  56. // release the disks that were locked
  57. if (!success)
  58. {
  59. for (int index = 0; index < lockIndex; index++)
  60. {
  61. disks[index].ReleaseLock();
  62. }
  63. }
  64. return success;
  65. }
  66. /// <summary>
  67. /// Will not persist across reboots
  68. /// </summary>
  69. public static bool OfflineAllOrNone(List<PhysicalDisk> disks)
  70. {
  71. bool success = true;
  72. int offlineIndex;
  73. for (offlineIndex = 0; offlineIndex < disks.Count; offlineIndex++)
  74. {
  75. success = disks[offlineIndex].SetOnlineStatus(false, false);
  76. if (!success)
  77. {
  78. break;
  79. }
  80. }
  81. // online the disks that were offlined
  82. if (!success)
  83. {
  84. for (int index = 0; index < offlineIndex; index++)
  85. {
  86. disks[index].SetOnlineStatus(true, false);
  87. }
  88. }
  89. return success;
  90. }
  91. }
  92. }