root/trunk/Updater/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs @ 597

Wersja 597, 8.3 KB (wprowadzona przez marek, 17 years temu)

re #165

Line 
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
36using System;
37using System.IO;
38using System.Text;
39
40using ICSharpCode.SharpZipLib.Core;
41
42namespace ICSharpCode.SharpZipLib.Zip
43{
44        /// <summary>
45        /// WindowsNameTransform transforms ZipFile names to windows compatible ones.
46        /// </summary>
47        public class WindowsNameTransform : INameTransform
48        {
49                /// <summary>
50                /// Initialises a new instance of <see cref="WindowsNameTransform"/>
51                /// </summary>
52                /// <param name="baseDirectory"></param>
53                public WindowsNameTransform(string baseDirectory)
54                {
55                        if ( baseDirectory == null ) {
56                                throw new ArgumentNullException("baseDirectory", "Directory name is invalid");
57                        }
58
59                        BaseDirectory = baseDirectory;
60                }
61               
62                /// <summary>
63                /// Initialise a default instance of <see cref="WindowsNameTransform"/>
64                /// </summary>
65                public WindowsNameTransform()
66                {
67                        // Do nothing.
68                }
69               
70                /// <summary>
71                /// Gets or sets a value containing the target directory to prefix values with.
72                /// </summary>
73                public string BaseDirectory
74                {
75                        get { return baseDirectory_; }
76                        set {
77                                if ( value == null ) {
78                                        throw new ArgumentNullException("value");
79                                }
80
81                                baseDirectory_ = Path.GetFullPath(value);
82                        }
83                }
84               
85                /// <summary>
86                /// Gets or sets a value indicating wether paths on incoming values should be removed.
87                /// </summary>
88                public bool TrimIncomingPaths
89                {
90                        get { return trimIncomingPaths_; }
91                        set { trimIncomingPaths_ = value; }
92                }
93               
94                /// <summary>
95                /// Transform a Zip directory name to a windows directory name.
96                /// </summary>
97                /// <param name="name">The directory name to transform.</param>
98                /// <returns>The transformed name.</returns>
99                public string TransformDirectory(string name)
100                {
101                        name = TransformFile(name);
102                        if (name.Length > 0) {
103                                while ( name.EndsWith(@"\") ) {
104                                        name = name.Remove(name.Length - 1, 1);
105                                }
106                        }
107                        else {
108                                throw new ZipException("Cannot have an empty directory name");
109                        }
110                        return name;
111                }
112               
113                /// <summary>
114                /// Transform a Zip format file name to a windows style one.
115                /// </summary>
116                /// <param name="name">The file name to transform.</param>
117                /// <returns>The transformed name.</returns>
118                public string TransformFile(string name)
119                {
120                        if (name != null) {
121                                name = MakeValidName(name, replacementChar_);
122                               
123                                if ( trimIncomingPaths_ ) {
124                                        name = Path.GetFileName(name);
125                                }
126                               
127                                // This may exceed windows length restrictions.
128                                // Combine will throw a PathTooLongException in that case.
129                                if ( baseDirectory_ != null ) {
130                                        name = Path.Combine(baseDirectory_, name);
131                                }       
132                        }
133                        else {
134                                name = string.Empty;
135                        }
136                        return name;
137                }
138               
139                /// <summary>
140                /// Test a name to see if it is a valid name for a windows filename as extracted from a Zip archive.
141                /// </summary>
142                /// <param name="name">The name to test.</param>
143                /// <returns>Returns true if the name is a valid zip name; false otherwise.</returns>
144                /// <remarks>The filename isnt a true windows path in some fundamental ways like no absolute paths, no rooted paths etc.</remarks>
145                public static bool IsValidName(string name)
146                {
147                        bool result =
148                                (name != null) &&
149                                (name.Length <= MaxPath) &&
150                                (string.Compare(name, MakeValidName(name, '_')) == 0)
151                                ;
152
153                        return result;
154                }
155
156                /// <summary>
157                /// Initialise static class information.
158                /// </summary>
159                static WindowsNameTransform()
160                {
161                        char[] invalidPathChars;
162
163#if NET_1_0 || NET_1_1 || NETCF_1_0
164                        invalidPathChars = Path.InvalidPathChars;
165#else
166                        invalidPathChars = Path.GetInvalidPathChars();
167#endif
168                        int howMany = invalidPathChars.Length + 3;
169
170                        InvalidEntryChars = new char[howMany];
171                        Array.Copy(invalidPathChars, 0, InvalidEntryChars, 0, invalidPathChars.Length);
172                        InvalidEntryChars[howMany - 1] = '*';
173                        InvalidEntryChars[howMany - 2] = '?';
174                        InvalidEntryChars[howMany - 2] = ':';
175                }
176
177                /// <summary>
178                /// Force a name to be valid by replacing invalid characters with a fixed value
179                /// </summary>
180                /// <param name="name">The name to make valid</param>
181                /// <param name="replacement">The replacement character to use for any invalid characters.</param>
182                /// <returns>Returns a valid name</returns>
183                public static string MakeValidName(string name, char replacement)
184                {
185                        if ( name == null ) {
186                                throw new ArgumentNullException("name");
187                        }
188                       
189                        name = WindowsPathUtils.DropPathRoot(name.Replace("/", @"\"));
190
191                        // Drop any leading slashes.
192                        while ( (name.Length > 0) && (name[0] == '\\')) {
193                                name = name.Remove(0, 1);
194                        }
195
196                        // Drop any trailing slashes.
197                        while ( (name.Length > 0) && (name[name.Length - 1] == '\\')) {
198                                name = name.Remove(name.Length - 1, 1);
199                        }
200
201                        // Convert consecutive \\ characters to \
202                        int index = name.IndexOf(@"\\");
203                        while (index >= 0) {
204                                name = name.Remove(index, 1);
205                                index = name.IndexOf(@"\\");
206                        }
207
208                        // Convert any invalid characters using the replacement one.
209                        index = name.IndexOfAny(InvalidEntryChars);
210                        if (index >= 0) {
211                                StringBuilder builder = new StringBuilder(name);
212
213                                while (index >= 0 ) {
214                                        builder[index] = replacement;
215
216                                        if (index >= name.Length) {
217                                                index = -1;
218                                        }
219                                        else {
220                                                index = name.IndexOfAny(InvalidEntryChars, index + 1);
221                                        }
222                                }
223                                name = builder.ToString();
224                        }
225                       
226                        // Check for names greater than MaxPath characters.
227                        // TODO: Were is CLR version of MaxPath defined?  Can't find it in Environment.
228                        if ( name.Length > MaxPath ) {
229                                throw new PathTooLongException();
230                        }
231                                       
232                        return name;
233                }
234
235                /// <summary>
236                /// Gets or set the character to replace invalid characters during transformations.
237                /// </summary>
238                public char Replacement
239                {
240                        get { return replacementChar_; }
241                        set {
242                                for ( int i = 0; i < InvalidEntryChars.Length; ++i ) {
243                                        if ( InvalidEntryChars[i] == value ) {
244                                                throw new ArgumentException("invalid path character");
245                                        }
246                                }
247
248                                if ((value == '\\') || (value == '/')) {
249                                        throw new ArgumentException("invalid replacement character");
250                                }
251                               
252                                replacementChar_ = value;
253                        }
254                }
255               
256                /// <summary>
257                ///  The maximum windows path name permitted.
258                /// </summary>
259                /// <remarks>This may not valid for all windows systems - CE?, etc but I cant find the equivalent in the CLR.</remarks>
260                const int MaxPath = 260;
261               
262                #region Instance Fields
263                string baseDirectory_;
264                bool trimIncomingPaths_;
265                char replacementChar_ = '_';
266                #endregion
267               
268                #region Class Fields
269                static readonly char[] InvalidEntryChars;
270                #endregion
271        }
272}
Notatka: Zobacz TracBrowser aby uzyskać więcej informacji.