LockHelper.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /* Copyright (C) 2014-2016 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.Text;
  10. using DiskAccessLibrary;
  11. namespace DiskAccessLibrary
  12. {
  13. public enum LockStatus
  14. {
  15. Success,
  16. CannotLockDisk,
  17. CannotLockVolume,
  18. }
  19. public partial class LockHelper
  20. {
  21. /// <summary>
  22. /// Will lock physical basic disk and all volumes on it.
  23. /// If the operation is not completed successfully, all locks will be releases.
  24. /// </summary>
  25. public static LockStatus LockBasicDiskAndVolumesOrNone(PhysicalDisk disk)
  26. {
  27. bool success = disk.ExclusiveLock();
  28. if (!success)
  29. {
  30. return LockStatus.CannotLockDisk;
  31. }
  32. List<Partition> partitions = BasicDiskHelper.GetPartitions(disk);
  33. List<Guid> volumeGuids = new List<Guid>();
  34. foreach (Partition partition in partitions)
  35. {
  36. Guid? windowsVolumeGuid = WindowsVolumeHelper.GetWindowsVolumeGuid(partition);
  37. if (windowsVolumeGuid.HasValue)
  38. {
  39. volumeGuids.Add(windowsVolumeGuid.Value);
  40. }
  41. else
  42. {
  43. return LockStatus.CannotLockVolume;
  44. }
  45. }
  46. success = LockAllVolumesOrNone(volumeGuids);
  47. if (!success)
  48. {
  49. disk.ReleaseLock();
  50. return LockStatus.CannotLockVolume;
  51. }
  52. return LockStatus.Success;
  53. }
  54. public static void UnlockBasicDiskAndVolumes(PhysicalDisk disk)
  55. {
  56. List<Partition> partitions = BasicDiskHelper.GetPartitions(disk);
  57. foreach (Partition partition in partitions)
  58. {
  59. Guid? windowsVolumeGuid = WindowsVolumeHelper.GetWindowsVolumeGuid(partition);
  60. if (windowsVolumeGuid.HasValue)
  61. {
  62. WindowsVolumeManager.ReleaseLock(windowsVolumeGuid.Value);
  63. }
  64. }
  65. disk.ReleaseLock();
  66. }
  67. public static bool LockAllVolumesOrNone(List<Guid> volumeGuids)
  68. {
  69. bool success = true;
  70. int lockIndex;
  71. for (lockIndex = 0; lockIndex < volumeGuids.Count; lockIndex++)
  72. {
  73. success = WindowsVolumeManager.ExclusiveLock(volumeGuids[lockIndex]);
  74. if (!success)
  75. {
  76. break;
  77. }
  78. }
  79. if (!success)
  80. {
  81. // release the volumes that were locked
  82. for (int index = 0; index < lockIndex; index++)
  83. {
  84. WindowsVolumeManager.ReleaseLock(volumeGuids[lockIndex]);
  85. }
  86. }
  87. return success;
  88. }
  89. }
  90. }