You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

file_utils.cs 2.4 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using SharpCompress.Common;
  2. using SharpCompress.Readers;
  3. using System;
  4. using System.IO;
  5. namespace Tensorflow.Hub
  6. {
  7. internal static class file_utils
  8. {
  9. //public static void extract_file(TarInputStream tgz, TarEntry tarInfo, string dstPath, uint bufferSize = 10 << 20, Action<long> logFunction = null)
  10. //{
  11. // using (var src = tgz.GetNextEntry() == tarInfo ? tgz : null)
  12. // {
  13. // if (src is null)
  14. // {
  15. // return;
  16. // }
  17. // using (var dst = File.Create(dstPath))
  18. // {
  19. // var buffer = new byte[bufferSize];
  20. // int count;
  21. // while ((count = src.Read(buffer, 0, buffer.Length)) > 0)
  22. // {
  23. // dst.Write(buffer, 0, count);
  24. // logFunction?.Invoke(count);
  25. // }
  26. // }
  27. // }
  28. //}
  29. public static void extract_tarfile_to_destination(Stream fileobj, string dst_path, Action<long> logFunction = null)
  30. {
  31. using (IReader reader = ReaderFactory.Open(fileobj))
  32. {
  33. while (reader.MoveToNextEntry())
  34. {
  35. if (!reader.Entry.IsDirectory)
  36. {
  37. reader.WriteEntryToDirectory(
  38. dst_path,
  39. new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }
  40. );
  41. }
  42. }
  43. }
  44. }
  45. public static string merge_relative_path(string dstPath, string relPath)
  46. {
  47. var cleanRelPath = Path.GetFullPath(relPath).TrimStart('/', '\\');
  48. if (cleanRelPath == ".")
  49. {
  50. return dstPath;
  51. }
  52. if (cleanRelPath.StartsWith("..") || Path.IsPathRooted(cleanRelPath))
  53. {
  54. throw new InvalidDataException($"Relative path '{relPath}' is invalid.");
  55. }
  56. var merged = Path.Combine(dstPath, cleanRelPath);
  57. if (!merged.StartsWith(dstPath))
  58. {
  59. throw new InvalidDataException($"Relative path '{relPath}' is invalid. Failed to merge with '{dstPath}'.");
  60. }
  61. return merged;
  62. }
  63. }
  64. }