BasicDiskHelper.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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.Text;
  10. using Utilities;
  11. namespace DiskAccessLibrary
  12. {
  13. public class BasicDiskHelper
  14. {
  15. public static List<Partition> GetPartitions(Disk disk)
  16. {
  17. List<Partition> result = new List<Partition>();
  18. MasterBootRecord mbr = MasterBootRecord.ReadFromDisk(disk);
  19. if (mbr != null)
  20. {
  21. if (!mbr.IsGPTBasedDisk)
  22. {
  23. for (int index = 0; index < mbr.PartitionTable.Length; index++)
  24. {
  25. PartitionTableEntry entry = mbr.PartitionTable[index];
  26. if (entry.SectorCountLBA > 0)
  27. {
  28. long size = entry.SectorCountLBA * disk.BytesPerSector;
  29. MBRPartition partition = new MBRPartition(entry.PartitionType, disk, entry.FirstSectorLBA, size);
  30. result.Add(partition);
  31. }
  32. }
  33. }
  34. else
  35. {
  36. List<GuidPartitionEntry> entries = GuidPartitionTable.ReadEntriesFromDisk(disk);
  37. if (entries != null)
  38. {
  39. foreach (GuidPartitionEntry entry in entries)
  40. {
  41. GPTPartition partition = new GPTPartition(entry.PartitionGuid, entry.PartitionTypeGuid, entry.PartitionName, disk, (long)entry.FirstLBA, (long)(entry.SizeLBA * (uint)disk.BytesPerSector));
  42. result.Add(partition);
  43. }
  44. }
  45. }
  46. }
  47. return result;
  48. }
  49. public static Partition GetPartitionByStartOffset(Disk disk, long firstSector)
  50. {
  51. List<Partition> partitions = BasicDiskHelper.GetPartitions(disk);
  52. foreach (Partition partition in partitions)
  53. {
  54. if (partition.FirstSector == firstSector)
  55. {
  56. return partition;
  57. }
  58. }
  59. return null;
  60. }
  61. }
  62. }