FileTimeHelper.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /* Copyright (C) 2014-2017 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 Utilities;
  10. namespace SMBLibrary
  11. {
  12. public class FileTimeHelper
  13. {
  14. public static readonly DateTime MinFileTimeValue = new DateTime(1601, 1, 1);
  15. public static DateTime ReadFileTime(byte[] buffer, int offset)
  16. {
  17. long span = LittleEndianConverter.ToInt64(buffer, offset);
  18. if (span >= 0)
  19. {
  20. return DateTime.FromFileTimeUtc(span);
  21. }
  22. else
  23. {
  24. throw new System.IO.InvalidDataException("FILETIME cannot be negative");
  25. }
  26. }
  27. public static DateTime ReadFileTime(byte[] buffer, ref int offset)
  28. {
  29. offset += 8;
  30. return ReadFileTime(buffer, offset - 8);
  31. }
  32. public static void WriteFileTime(byte[] buffer, int offset, DateTime time)
  33. {
  34. long span = time.ToFileTimeUtc();
  35. LittleEndianWriter.WriteInt64(buffer, offset, span);
  36. }
  37. public static void WriteFileTime(byte[] buffer, ref int offset, DateTime time)
  38. {
  39. WriteFileTime(buffer, offset, time);
  40. offset += 8;
  41. }
  42. public static DateTime? ReadNullableFileTime(byte[] buffer, int offset)
  43. {
  44. long span = LittleEndianConverter.ToInt64(buffer, offset);
  45. if (span > 0)
  46. {
  47. return DateTime.FromFileTimeUtc(span);
  48. }
  49. else
  50. {
  51. return null;
  52. }
  53. }
  54. public static DateTime? ReadNullableFileTime(byte[] buffer, ref int offset)
  55. {
  56. offset += 8;
  57. return ReadNullableFileTime(buffer, offset - 8);
  58. }
  59. public static void WriteFileTime(byte[] buffer, int offset, DateTime? time)
  60. {
  61. long span = 0;
  62. if (time.HasValue)
  63. {
  64. span = time.Value.ToFileTimeUtc();
  65. }
  66. LittleEndianWriter.WriteInt64(buffer, offset, span);
  67. }
  68. public static void WriteFileTime(byte[] buffer, ref int offset, DateTime? time)
  69. {
  70. WriteFileTime(buffer, offset, time);
  71. offset += 8;
  72. }
  73. }
  74. }