WindowsNameTransform.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // WindowsNameTransform.cs
  2. //
  3. // Copyright 2007 John Reilly
  4. //
  5. // This program is free software; you can redistribute it and/or
  6. // modify it under the terms of the GNU General Public License
  7. // as published by the Free Software Foundation; either version 2
  8. // of the License, or (at your option) any later version.
  9. //
  10. // This program is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU General Public License
  16. // along with this program; if not, write to the Free Software
  17. // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  18. //
  19. // Linking this library statically or dynamically with other modules is
  20. // making a combined work based on this library. Thus, the terms and
  21. // conditions of the GNU General Public License cover the whole
  22. // combination.
  23. //
  24. // As a special exception, the copyright holders of this library give you
  25. // permission to link this library with independent modules to produce an
  26. // executable, regardless of the license terms of these independent
  27. // modules, and to copy and distribute the resulting executable under
  28. // terms of your choice, provided that you also meet, for each linked
  29. // independent module, the terms and conditions of the license of that
  30. // module. An independent module is a module which is not derived from
  31. // or based on this library. If you modify this library, you may extend
  32. // this exception to your version of the library, but you are not
  33. // obligated to do so. If you do not wish to do so, delete this
  34. // exception statement from your version.
  35. using System;
  36. using System.IO;
  37. using System.Text;
  38. using CommonMPQ.SharpZipLib.Core;
  39. namespace CommonMPQ.SharpZipLib.Zip
  40. {
  41. /// <summary>
  42. /// WindowsNameTransform transforms <see cref="ZipFile"/> names to windows compatible ones.
  43. /// </summary>
  44. public class WindowsNameTransform : INameTransform
  45. {
  46. /// <summary>
  47. /// Initialises a new instance of <see cref="WindowsNameTransform"/>
  48. /// </summary>
  49. /// <param name="baseDirectory"></param>
  50. public WindowsNameTransform(string baseDirectory)
  51. {
  52. if ( baseDirectory == null ) {
  53. throw new ArgumentNullException("baseDirectory", "Directory name is invalid");
  54. }
  55. BaseDirectory = baseDirectory;
  56. }
  57. /// <summary>
  58. /// Initialise a default instance of <see cref="WindowsNameTransform"/>
  59. /// </summary>
  60. public WindowsNameTransform()
  61. {
  62. // Do nothing.
  63. }
  64. /// <summary>
  65. /// Gets or sets a value containing the target directory to prefix values with.
  66. /// </summary>
  67. public string BaseDirectory
  68. {
  69. get { return _baseDirectory; }
  70. set {
  71. if ( value == null ) {
  72. throw new ArgumentNullException("value");
  73. }
  74. _baseDirectory = Path.GetFullPath(value);
  75. }
  76. }
  77. /// <summary>
  78. /// Gets or sets a value indicating wether paths on incoming values should be removed.
  79. /// </summary>
  80. public bool TrimIncomingPaths
  81. {
  82. get { return _trimIncomingPaths; }
  83. set { _trimIncomingPaths = value; }
  84. }
  85. /// <summary>
  86. /// Transform a Zip directory name to a windows directory name.
  87. /// </summary>
  88. /// <param name="name">The directory name to transform.</param>
  89. /// <returns>The transformed name.</returns>
  90. public string TransformDirectory(string name)
  91. {
  92. name = TransformFile(name);
  93. if (name.Length > 0) {
  94. while ( name.EndsWith(Path.DirectorySeparatorChar.ToString()) ) {
  95. name = name.Remove(name.Length - 1, 1);
  96. }
  97. }
  98. else {
  99. throw new ZipException("Cannot have an empty directory name");
  100. }
  101. return name;
  102. }
  103. /// <summary>
  104. /// Transform a Zip format file name to a windows style one.
  105. /// </summary>
  106. /// <param name="name">The file name to transform.</param>
  107. /// <returns>The transformed name.</returns>
  108. public string TransformFile(string name)
  109. {
  110. if (name != null) {
  111. name = MakeValidName(name, _replacementChar);
  112. if ( _trimIncomingPaths ) {
  113. name = Path.GetFileName(name);
  114. }
  115. // This may exceed windows length restrictions.
  116. // Combine will throw a PathTooLongException in that case.
  117. if ( _baseDirectory != null ) {
  118. name = Path.Combine(_baseDirectory, name);
  119. }
  120. }
  121. else {
  122. name = string.Empty;
  123. }
  124. return name;
  125. }
  126. /// <summary>
  127. /// Test a name to see if it is a valid name for a windows filename as extracted from a Zip archive.
  128. /// </summary>
  129. /// <param name="name">The name to test.</param>
  130. /// <returns>Returns true if the name is a valid zip name; false otherwise.</returns>
  131. /// <remarks>The filename isnt a true windows path in some fundamental ways like no absolute paths, no rooted paths etc.</remarks>
  132. public static bool IsValidName(string name)
  133. {
  134. bool result =
  135. (name != null) &&
  136. (name.Length <= MaxPath) &&
  137. (string.Compare(name, MakeValidName(name, '_')) == 0)
  138. ;
  139. return result;
  140. }
  141. /// <summary>
  142. /// Initialise static class information.
  143. /// </summary>
  144. static WindowsNameTransform()
  145. {
  146. char[] invalidPathChars;
  147. #if NET_1_0 || NET_1_1 || NETCF_1_0
  148. invalidPathChars = Path.InvalidPathChars;
  149. #else
  150. invalidPathChars = Path.GetInvalidPathChars();
  151. #endif
  152. int howMany = invalidPathChars.Length + 3;
  153. InvalidEntryChars = new char[howMany];
  154. Array.Copy(invalidPathChars, 0, InvalidEntryChars, 0, invalidPathChars.Length);
  155. InvalidEntryChars[howMany - 1] = '*';
  156. InvalidEntryChars[howMany - 2] = '?';
  157. InvalidEntryChars[howMany - 3] = ':';
  158. }
  159. /// <summary>
  160. /// Force a name to be valid by replacing invalid characters with a fixed value
  161. /// </summary>
  162. /// <param name="name">The name to make valid</param>
  163. /// <param name="replacement">The replacement character to use for any invalid characters.</param>
  164. /// <returns>Returns a valid name</returns>
  165. public static string MakeValidName(string name, char replacement)
  166. {
  167. if ( name == null ) {
  168. throw new ArgumentNullException("name");
  169. }
  170. name = WindowsPathUtils.DropPathRoot(name.Replace("/", Path.DirectorySeparatorChar.ToString()));
  171. // Drop any leading slashes.
  172. while ( (name.Length > 0) && (name[0] == Path.DirectorySeparatorChar)) {
  173. name = name.Remove(0, 1);
  174. }
  175. // Drop any trailing slashes.
  176. while ( (name.Length > 0) && (name[name.Length - 1] == Path.DirectorySeparatorChar)) {
  177. name = name.Remove(name.Length - 1, 1);
  178. }
  179. // Convert consecutive \\ characters to \
  180. int index = name.IndexOf(string.Format("{0}{0}", Path.DirectorySeparatorChar));
  181. while (index >= 0) {
  182. name = name.Remove(index, 1);
  183. index = name.IndexOf(Path.DirectorySeparatorChar);
  184. }
  185. // Convert any invalid characters using the replacement one.
  186. index = name.IndexOfAny(InvalidEntryChars);
  187. if (index >= 0) {
  188. StringBuilder builder = new StringBuilder(name);
  189. while (index >= 0 ) {
  190. builder[index] = replacement;
  191. if (index >= name.Length) {
  192. index = -1;
  193. }
  194. else {
  195. index = name.IndexOfAny(InvalidEntryChars, index + 1);
  196. }
  197. }
  198. name = builder.ToString();
  199. }
  200. // Check for names greater than MaxPath characters.
  201. // TODO: Were is CLR version of MaxPath defined? Can't find it in Environment.
  202. if ( name.Length > MaxPath ) {
  203. throw new PathTooLongException();
  204. }
  205. return name;
  206. }
  207. /// <summary>
  208. /// Gets or set the character to replace invalid characters during transformations.
  209. /// </summary>
  210. public char Replacement
  211. {
  212. get { return _replacementChar; }
  213. set {
  214. for ( int i = 0; i < InvalidEntryChars.Length; ++i ) {
  215. if ( InvalidEntryChars[i] == value ) {
  216. throw new ArgumentException("invalid path character");
  217. }
  218. }
  219. if ((value == Path.DirectorySeparatorChar) || (value == Path.AltDirectorySeparatorChar)) {
  220. throw new ArgumentException("invalid replacement character");
  221. }
  222. _replacementChar = value;
  223. }
  224. }
  225. /// <summary>
  226. /// The maximum windows path name permitted.
  227. /// </summary>
  228. /// <remarks>This may not valid for all windows systems - CE?, etc but I cant find the equivalent in the CLR.</remarks>
  229. const int MaxPath = 260;
  230. #region Instance Fields
  231. string _baseDirectory;
  232. bool _trimIncomingPaths;
  233. char _replacementChar = '_';
  234. #endregion
  235. #region Class Fields
  236. static readonly char[] InvalidEntryChars;
  237. #endregion
  238. }
  239. }