-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathFastDirectoryEnumerator.cs
503 lines (440 loc) · 19.7 KB
/
FastDirectoryEnumerator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
/*
This code file was downloaded from the following Code Project article:
A Faster Directory Enumerator
By wilsone8, 27 Aug 2009
http://www.codeproject.com/Articles/38959/A-Faster-Directory-Enumerator
It was modified to move it into the RMLib namespace, and by moving some
of the platform specific code to the NativeMethods class
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
namespace RandM.RMLib
{
/// <summary>
/// Contains information about a file returned by the
/// <see cref="FastDirectoryEnumerator"/> class.
/// </summary>
[Serializable]
public class FileData
{
/// <summary>
/// Attributes of the file.
/// </summary>
public readonly FileAttributes Attributes;
public DateTime CreationTime
{
get { return this.CreationTimeUtc.ToLocalTime(); }
}
/// <summary>
/// File creation time in UTC
/// </summary>
public readonly DateTime CreationTimeUtc;
/// <summary>
/// Gets the last access time in local time.
/// </summary>
public DateTime LastAccesTime
{
get { return this.LastAccessTimeUtc.ToLocalTime(); }
}
/// <summary>
/// File last access time in UTC
/// </summary>
public readonly DateTime LastAccessTimeUtc;
/// <summary>
/// Gets the last access time in local time.
/// </summary>
public DateTime LastWriteTime
{
get { return this.LastWriteTimeUtc.ToLocalTime(); }
}
/// <summary>
/// File last write time in UTC
/// </summary>
public readonly DateTime LastWriteTimeUtc;
/// <summary>
/// Size of the file in bytes
/// </summary>
public readonly long Size;
/// <summary>
/// Name of the file
/// </summary>
public readonly string Name;
/// <summary>
/// Full path to the file.
/// </summary>
public readonly string Path;
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
return this.Name;
}
/// <summary>
/// Initializes a new instance of the <see cref="FileData"/> class.
/// </summary>
/// <param name="dir">The directory that the file is stored at</param>
/// <param name="findData">WIN32_FIND_DATA structure that this
/// object wraps.</param>
public FileData(string dir, NativeMethods.WIN32_FIND_DATA findData)
{
this.Attributes = findData.dwFileAttributes;
this.CreationTimeUtc = ConvertDateTime(findData.ftCreationTime_dwHighDateTime,
findData.ftCreationTime_dwLowDateTime);
this.LastAccessTimeUtc = ConvertDateTime(findData.ftLastAccessTime_dwHighDateTime,
findData.ftLastAccessTime_dwLowDateTime);
this.LastWriteTimeUtc = ConvertDateTime(findData.ftLastWriteTime_dwHighDateTime,
findData.ftLastWriteTime_dwLowDateTime);
this.Size = CombineHighLowInts(findData.nFileSizeHigh, findData.nFileSizeLow);
this.Name = findData.cFileName;
this.Path = System.IO.Path.Combine(dir, findData.cFileName);
}
public static long CombineHighLowInts(uint high, uint low)
{
return (((long)high) << 0x20) | low;
}
public static DateTime ConvertDateTime(uint high, uint low)
{
long fileTime = CombineHighLowInts(high, low);
return DateTime.FromFileTimeUtc(fileTime);
}
}
/// <summary>
/// A fast enumerator of files in a directory. Use this if you need to get attributes for
/// all files in a directory.
/// </summary>
/// <remarks>
/// This enumerator is substantially faster than using <see cref="Directory.GetFiles(string)"/>
/// and then creating a new FileInfo object for each path. Use this version when you
/// will need to look at the attibutes of each file returned (for example, you need
/// to check each file in a directory to see if it was modified after a specific date).
/// </remarks>
public static class FastDirectoryEnumerator
{
/// <summary>
/// Gets <see cref="FileData"/> for all the files in a directory.
/// </summary>
/// <param name="path">The path to search.</param>
/// <returns>An object that implements <see cref="IEnumerable{FileData}"/> and
/// allows you to enumerate the files in the given directory.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is a null reference (Nothing in VB)
/// </exception>
public static IEnumerable<FileData> EnumerateFiles(string path)
{
return FastDirectoryEnumerator.EnumerateFiles(path, "*");
}
/// <summary>
/// Gets <see cref="FileData"/> for all the files in a directory that match a
/// specific filter.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="searchPattern">The search string to match against files in the path.</param>
/// <returns>An object that implements <see cref="IEnumerable{FileData}"/> and
/// allows you to enumerate the files in the given directory.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is a null reference (Nothing in VB)
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="filter"/> is a null reference (Nothing in VB)
/// </exception>
public static IEnumerable<FileData> EnumerateFiles(string path, string searchPattern)
{
return FastDirectoryEnumerator.EnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
/// <summary>
/// Gets <see cref="FileData"/> for all the files in a directory that
/// match a specific filter, optionally including all sub directories.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="searchPattern">The search string to match against files in the path.</param>
/// <param name="searchOption">
/// One of the SearchOption values that specifies whether the search
/// operation should include all subdirectories or only the current directory.
/// </param>
/// <returns>An object that implements <see cref="IEnumerable{FileData}"/> and
/// allows you to enumerate the files in the given directory.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is a null reference (Nothing in VB)
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="filter"/> is a null reference (Nothing in VB)
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="searchOption"/> is not one of the valid values of the
/// <see cref="System.IO.SearchOption"/> enumeration.
/// </exception>
public static IEnumerable<FileData> EnumerateFiles(string path, string searchPattern, SearchOption searchOption)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
if (searchPattern == null)
{
throw new ArgumentNullException("searchPattern");
}
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
{
throw new ArgumentOutOfRangeException("searchOption");
}
string fullPath = Path.GetFullPath(path);
return new FileEnumerable(fullPath, searchPattern, searchOption);
}
/// <summary>
/// Gets <see cref="FileData"/> for all the files in a directory that match a
/// specific filter.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="searchPattern">The search string to match against files in the path.</param>
/// <param name="searchOption">The options for the search</param>
/// <returns>An object that implements <see cref="IEnumerable{FileData}"/> and
/// allows you to enumerate the files in the given directory.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is a null reference (Nothing in VB)
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="filter"/> is a null reference (Nothing in VB)
/// </exception>
public static FileData[] GetFiles(string path, string searchPattern, SearchOption searchOption)
{
IEnumerable<FileData> e = FastDirectoryEnumerator.EnumerateFiles(path, searchPattern, searchOption);
List<FileData> list = new List<FileData>(e);
FileData[] retval = new FileData[list.Count];
list.CopyTo(retval);
return retval;
}
/// <summary>
/// Provides the implementation of the
/// <see cref="T:System.Collections.Generic.IEnumerable`1"/> interface
/// </summary>
private class FileEnumerable : IEnumerable<FileData>
{
private readonly string m_path;
private readonly string m_filter;
private readonly SearchOption m_searchOption;
/// <summary>
/// Initializes a new instance of the <see cref="FileEnumerable"/> class.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="filter">The search string to match against files in the path.</param>
/// <param name="searchOption">
/// One of the SearchOption values that specifies whether the search
/// operation should include all subdirectories or only the current directory.
/// </param>
public FileEnumerable(string path, string filter, SearchOption searchOption)
{
m_path = path;
m_filter = filter;
m_searchOption = searchOption;
}
#region IEnumerable<FileData> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can
/// be used to iterate through the collection.
/// </returns>
public IEnumerator<FileData> GetEnumerator()
{
return new FileEnumerator(m_path, m_filter, m_searchOption);
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be
/// used to iterate through the collection.
/// </returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new FileEnumerator(m_path, m_filter, m_searchOption);
}
#endregion
}
/// <summary>
/// Provides the implementation of the
/// <see cref="T:System.Collections.Generic.IEnumerator`1"/> interface
/// </summary>
[System.Security.SuppressUnmanagedCodeSecurity]
private class FileEnumerator : IEnumerator<FileData>
{
/// <summary>
/// Hold context information about where we current are in the directory search.
/// </summary>
private class SearchContext
{
public readonly string Path;
public Stack<string> SubdirectoriesToProcess;
public SearchContext(string path)
{
this.Path = path;
}
}
private string m_path;
private string m_filter;
private SearchOption m_searchOption;
private Stack<SearchContext> m_contextStack;
private SearchContext m_currentContext;
private NativeMethods.SafeFindHandle m_hndFindFile;
private NativeMethods.WIN32_FIND_DATA m_win_find_data = new NativeMethods.WIN32_FIND_DATA();
/// <summary>
/// Initializes a new instance of the <see cref="FileEnumerator"/> class.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="filter">The search string to match against files in the path.</param>
/// <param name="searchOption">
/// One of the SearchOption values that specifies whether the search
/// operation should include all subdirectories or only the current directory.
/// </param>
public FileEnumerator(string path, string filter, SearchOption searchOption)
{
m_path = path;
m_filter = filter;
m_searchOption = searchOption;
m_currentContext = new SearchContext(path);
if (m_searchOption == SearchOption.AllDirectories)
{
m_contextStack = new Stack<SearchContext>();
}
}
#region IEnumerator<FileData> Members
/// <summary>
/// Gets the element in the collection at the current position of the enumerator.
/// </summary>
/// <value></value>
/// <returns>
/// The element in the collection at the current position of the enumerator.
/// </returns>
public FileData Current
{
get { return new FileData(m_path, m_win_find_data); }
}
#endregion
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing,
/// or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (m_hndFindFile != null)
{
m_hndFindFile.Dispose();
}
}
#endregion
#region IEnumerator Members
/// <summary>
/// Gets the element in the collection at the current position of the enumerator.
/// </summary>
/// <value></value>
/// <returns>
/// The element in the collection at the current position of the enumerator.
/// </returns>
object System.Collections.IEnumerator.Current
{
get { return new FileData(m_path, m_win_find_data); }
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element;
/// false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public bool MoveNext()
{
bool retval = false;
//If the handle is null, this is first call to MoveNext in the current
// directory. In that case, start a new search.
if (m_currentContext.SubdirectoriesToProcess == null)
{
if (m_hndFindFile == null)
{
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, m_path).Demand();
string searchPath = Path.Combine(m_path, m_filter);
m_hndFindFile = NativeMethods.FindFirstFile(searchPath, m_win_find_data);
retval = !m_hndFindFile.IsInvalid;
}
else
{
//Otherwise, find the next item.
retval = NativeMethods.FindNextFile(m_hndFindFile, m_win_find_data);
}
}
//If the call to FindNextFile or FindFirstFile succeeded...
if (retval)
{
if (((FileAttributes)m_win_find_data.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory)
{
//Ignore folders for now. We call MoveNext recursively here to
// move to the next item that FindNextFile will return.
return MoveNext();
}
}
else if (m_searchOption == SearchOption.AllDirectories)
{
//SearchContext context = new SearchContext(m_hndFindFile, m_path);
//m_contextStack.Push(context);
//m_path = Path.Combine(m_path, m_win_find_data.cFileName);
//m_hndFindFile = null;
if (m_currentContext.SubdirectoriesToProcess == null)
{
string[] subDirectories = Directory.GetDirectories(m_path);
m_currentContext.SubdirectoriesToProcess = new Stack<string>(subDirectories);
}
if (m_currentContext.SubdirectoriesToProcess.Count > 0)
{
string subDir = m_currentContext.SubdirectoriesToProcess.Pop();
m_contextStack.Push(m_currentContext);
m_path = subDir;
m_hndFindFile = null;
m_currentContext = new SearchContext(m_path);
return MoveNext();
}
//If there are no more files in this directory and we are
// in a sub directory, pop back up to the parent directory and
// continue the search from there.
if (m_contextStack.Count > 0)
{
m_currentContext = m_contextStack.Pop();
m_path = m_currentContext.Path;
if (m_hndFindFile != null)
{
m_hndFindFile.Close();
m_hndFindFile = null;
}
return MoveNext();
}
}
return retval;
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public void Reset()
{
m_hndFindFile = null;
}
#endregion
}
}
}