WindowsNameTransform.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using ICSharpCode.SharpZipLib.Core;
  5. namespace ICSharpCode.SharpZipLib.Zip
  6. {
  7. /// <summary>
  8. /// WindowsNameTransform transforms <see cref="ZipFile"/> names to windows compatible ones.
  9. /// </summary>
  10. public class WindowsNameTransform : INameTransform
  11. {
  12. /// <summary>
  13. /// The maximum windows path name permitted.
  14. /// </summary>
  15. /// <remarks>This may not valid for all windows systems - CE?, etc but I cant find the equivalent in the CLR.</remarks>
  16. const int MaxPath = 260;
  17. string _baseDirectory;
  18. bool _trimIncomingPaths;
  19. char _replacementChar = '_';
  20. /// <summary>
  21. /// In this case we need Windows' invalid path characters.
  22. /// Path.GetInvalidPathChars() only returns a subset invalid on all platforms.
  23. /// </summary>
  24. static readonly char[] InvalidEntryChars = new char[] {
  25. '"', '<', '>', '|', '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
  26. '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f',
  27. '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016',
  28. '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d',
  29. '\u001e', '\u001f',
  30. // extra characters for masks, etc.
  31. '*', '?', ':'
  32. };
  33. /// <summary>
  34. /// Initialises a new instance of <see cref="WindowsNameTransform"/>
  35. /// </summary>
  36. /// <param name="baseDirectory"></param>
  37. public WindowsNameTransform(string baseDirectory)
  38. {
  39. if (baseDirectory == null) {
  40. throw new ArgumentNullException("nameof(baseDirectory)", "Directory name is invalid");
  41. }
  42. BaseDirectory = baseDirectory;
  43. }
  44. /// <summary>
  45. /// Initialise a default instance of <see cref="WindowsNameTransform"/>
  46. /// </summary>
  47. public WindowsNameTransform()
  48. {
  49. // Do nothing.
  50. }
  51. /// <summary>
  52. /// Gets or sets a value containing the target directory to prefix values with.
  53. /// </summary>
  54. public string BaseDirectory {
  55. get { return _baseDirectory; }
  56. set {
  57. if (value == null) {
  58. throw new ArgumentNullException("nameof(value)");
  59. }
  60. _baseDirectory = Path.GetFullPath(value);
  61. }
  62. }
  63. /// <summary>
  64. /// Gets or sets a value indicating wether paths on incoming values should be removed.
  65. /// </summary>
  66. public bool TrimIncomingPaths {
  67. get { return _trimIncomingPaths; }
  68. set { _trimIncomingPaths = value; }
  69. }
  70. /// <summary>
  71. /// Transform a Zip directory name to a windows directory name.
  72. /// </summary>
  73. /// <param name="name">The directory name to transform.</param>
  74. /// <returns>The transformed name.</returns>
  75. public string TransformDirectory(string name)
  76. {
  77. name = TransformFile(name);
  78. if (name.Length > 0) {
  79. while (name.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) {
  80. name = name.Remove(name.Length - 1, 1);
  81. }
  82. } else {
  83. throw new ZipException("Cannot have an empty directory name");
  84. }
  85. return name;
  86. }
  87. /// <summary>
  88. /// Transform a Zip format file name to a windows style one.
  89. /// </summary>
  90. /// <param name="name">The file name to transform.</param>
  91. /// <returns>The transformed name.</returns>
  92. public string TransformFile(string name)
  93. {
  94. if (name != null) {
  95. name = MakeValidName(name, _replacementChar);
  96. if (_trimIncomingPaths) {
  97. name = Path.GetFileName(name);
  98. }
  99. // This may exceed windows length restrictions.
  100. // Combine will throw a PathTooLongException in that case.
  101. if (_baseDirectory != null) {
  102. name = Path.Combine(_baseDirectory, name);
  103. }
  104. } else {
  105. name = string.Empty;
  106. }
  107. return name;
  108. }
  109. /// <summary>
  110. /// Test a name to see if it is a valid name for a windows filename as extracted from a Zip archive.
  111. /// </summary>
  112. /// <param name="name">The name to test.</param>
  113. /// <returns>Returns true if the name is a valid zip name; false otherwise.</returns>
  114. /// <remarks>The filename isnt a true windows path in some fundamental ways like no absolute paths, no rooted paths etc.</remarks>
  115. public static bool IsValidName(string name)
  116. {
  117. bool result =
  118. (name != null) &&
  119. (name.Length <= MaxPath) &&
  120. (string.Compare(name, MakeValidName(name, '_'), StringComparison.Ordinal) == 0)
  121. ;
  122. return result;
  123. }
  124. /// <summary>
  125. /// Force a name to be valid by replacing invalid characters with a fixed value
  126. /// </summary>
  127. /// <param name="name">The name to make valid</param>
  128. /// <param name="replacement">The replacement character to use for any invalid characters.</param>
  129. /// <returns>Returns a valid name</returns>
  130. public static string MakeValidName(string name, char replacement)
  131. {
  132. if (name == null) {
  133. throw new ArgumentNullException("nameof(name)");
  134. }
  135. name = WindowsPathUtils.DropPathRoot(name.Replace("/", Path.DirectorySeparatorChar.ToString()));
  136. // Drop any leading slashes.
  137. while ((name.Length > 0) && (name[0] == Path.DirectorySeparatorChar)) {
  138. name = name.Remove(0, 1);
  139. }
  140. // Drop any trailing slashes.
  141. while ((name.Length > 0) && (name[name.Length - 1] == Path.DirectorySeparatorChar)) {
  142. name = name.Remove(name.Length - 1, 1);
  143. }
  144. // Convert consecutive \\ characters to \
  145. int index = name.IndexOf(string.Format("{0}{0}", Path.DirectorySeparatorChar), StringComparison.Ordinal);
  146. while (index >= 0) {
  147. name = name.Remove(index, 1);
  148. index = name.IndexOf(string.Format("{0}{0}", Path.DirectorySeparatorChar), StringComparison.Ordinal);
  149. }
  150. // Convert any invalid characters using the replacement one.
  151. index = name.IndexOfAny(InvalidEntryChars);
  152. if (index >= 0) {
  153. var builder = new StringBuilder(name);
  154. while (index >= 0) {
  155. builder[index] = replacement;
  156. if (index >= name.Length) {
  157. index = -1;
  158. } else {
  159. index = name.IndexOfAny(InvalidEntryChars, index + 1);
  160. }
  161. }
  162. name = builder.ToString();
  163. }
  164. // Check for names greater than MaxPath characters.
  165. // TODO: Were is CLR version of MaxPath defined? Can't find it in Environment.
  166. if (name.Length > MaxPath) {
  167. throw new PathTooLongException();
  168. }
  169. return name;
  170. }
  171. /// <summary>
  172. /// Gets or set the character to replace invalid characters during transformations.
  173. /// </summary>
  174. public char Replacement {
  175. get { return _replacementChar; }
  176. set {
  177. for (int i = 0; i < InvalidEntryChars.Length; ++i) {
  178. if (InvalidEntryChars[i] == value) {
  179. throw new ArgumentException("invalid path character");
  180. }
  181. }
  182. if ((value == Path.DirectorySeparatorChar) || (value == Path.AltDirectorySeparatorChar)) {
  183. throw new ArgumentException("invalid replacement character");
  184. }
  185. _replacementChar = value;
  186. }
  187. }
  188. }
  189. }