GuidPartitionEntry.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 GuidPartitionEntry
  14. {
  15. // length is defined in GPT Header
  16. public Guid PartitionTypeGuid;
  17. public Guid PartitionGuid;
  18. public ulong FirstLBA;
  19. public ulong LastLBA;
  20. public ulong AttributeFlags;
  21. public string PartitionName;
  22. public int EntryIndex; // We may use this later for write operations
  23. public GuidPartitionEntry()
  24. {
  25. PartitionName = String.Empty;
  26. }
  27. public GuidPartitionEntry(byte[] buffer, int offset)
  28. {
  29. PartitionTypeGuid = LittleEndianConverter.ToGuid(buffer, offset + 0);
  30. PartitionGuid = LittleEndianConverter.ToGuid(buffer, offset + 16);
  31. FirstLBA = LittleEndianConverter.ToUInt64(buffer, offset + 32);
  32. LastLBA = LittleEndianConverter.ToUInt64(buffer, offset + 40);
  33. AttributeFlags = LittleEndianConverter.ToUInt64(buffer, offset + 48);
  34. PartitionName = UnicodeEncoding.Unicode.GetString(ByteReader.ReadBytes(buffer, offset + 56, 72)).TrimEnd('\0');
  35. }
  36. public void WriteBytes(byte[] buffer, int offset)
  37. {
  38. LittleEndianWriter.WriteGuidBytes(buffer, offset + 0, PartitionTypeGuid);
  39. LittleEndianWriter.WriteGuidBytes(buffer, offset + 16, PartitionGuid);
  40. LittleEndianWriter.WriteUInt64(buffer, offset + 32, FirstLBA);
  41. LittleEndianWriter.WriteUInt64(buffer, offset + 40, LastLBA);
  42. LittleEndianWriter.WriteUInt64(buffer, offset + 48, AttributeFlags);
  43. while (PartitionName.Length < 36)
  44. {
  45. PartitionName += "\0";
  46. }
  47. ByteWriter.WriteUTF16String(buffer, offset + 56, PartitionName, 36);
  48. }
  49. public ulong SizeLBA
  50. {
  51. get
  52. {
  53. return LastLBA - FirstLBA + 1;
  54. }
  55. }
  56. public static void WriteToDisk(Disk disk, GuidPartitionTableHeader header, GuidPartitionEntry entry)
  57. {
  58. long sectorIndex = (long)header.PartitionEntriesLBA + entry.EntryIndex * header.SizeOfPartitionEntry / disk.BytesPerSector;
  59. int entriesPerSector = (int)(disk.BytesPerSector / header.SizeOfPartitionEntry);
  60. int indexInSector = (int)(entry.EntryIndex % entriesPerSector);
  61. byte[] buffer = disk.ReadSector(sectorIndex);
  62. entry.WriteBytes(buffer, indexInSector * (int)header.SizeOfPartitionEntry);
  63. disk.WriteSectors(sectorIndex, buffer);
  64. }
  65. }
  66. }