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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
|
namespace DotNetExpansions.ParallelSearch
{
/// <summary>
/// Gibt an ob die Suche nach dem ersten Fund abgebrochen werden soll,
/// oder ob die Suche fortgeführt werden soll bis alle Pfade durchsucht sind.
/// </summary>
public enum FindMode
{
/// <summary>
/// Stoppt die Suche wenn die erste Datei in einem der angegebenen Ordner gefunden wurde,
/// die dem Suchkriterium entspricht.
/// </summary>
FindOne,
/// <summary>
/// Findet alle Dateien in allen angegebenen Ordnern, die dem Suchkriterium entsprechen.
/// </summary>
FindAll
}
}
//=========================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Permissions;
using System.Threading;
namespace DotNetExpansions.ParallelSearch
{
/// <summary>
/// Sucht Dateien und/oder nach bestimmtem Inhalt in Dateien.
/// Es können beliebig viele Suchstrings übergeben werden.
/// Diese werden nach Laufwerksbuchstabe gruppiert.
/// Alle Gruppen werden parallel durchsucht.
/// Somit bietet diese Klasse eine optimale Performance.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
///using System;
///using System.Collections.Generic;
///using System.IO;
///using DotNetExpansions.ParallelSearch;
///
///namespace ParallelSearchDemo
///{
/// class Program
/// {
/// public static void Main()
/// {
/// const bool ignoreExceptions = true;
/// var parallelFileSearcher = new ParallelFileSearcher(ignoreExceptions);
/// parallelFileSearcher.FoundFile += FileFoundHandler;
/// parallelFileSearcher.CallOutUnauthorizedAccess += ShowCurrentlyDeniedAccess;
///
/// // Make a container for the search sets.
/// List<SearchSet> searchSets = new List<SearchSet>();
///
/// // Generate a search set...
/// var searchSet = new SearchSet(
/// new DirectoryInfo(@"C:\System Volume Information"),
/// SearchOption.TopDirectoryOnly);
/// // ...and add it to the container.
/// searchSets.Add(searchSet);
///
/// // Generate another search set...
/// searchSet = new SearchSet(
/// new DirectoryInfo(@"I:\Developer\VS2008\Projects\DotNetExpansions\Demos"),
/// SearchOption.AllDirectories);
/// // ...and add it to the container.
/// searchSets.Add(searchSet);
///
/// // Define search-parameters.
/// string filenamePattern = "*.cs";
/// string contentToSearchFor = ""; // Could also be null.
///
/// // Start the search with those parameters.
/// Console.WriteLine("Search in progress. Please wait...");
/// List<FileInfo> fileInfos =
/// parallelFileSearcher.FindFiles(
/// searchSets, filenamePattern, contentToSearchFor, FindMode.FindAll);
/// // Do something with fileInfos like, for instance, delete those files.
///
/// // Verhindert das selbsttätige Schließen des Konsolenfensters.
/// Console.WriteLine("\nPress any key to terminate the program.");
/// Console.ReadKey();
/// }
///
/// private static void ShowCurrentlyDeniedAccess(string fullName)
/// {
/// Console.WriteLine("Access denied on " + fullName);
/// }
///
/// private static void FileFoundHandler(string fullFileName)
/// {
/// Console.WriteLine(fullFileName);
/// }
/// }
///}
///
/// /* Sample Output:
/// g:\projektinterkosmos\interkosmos\codecontractstrials\codecontractstrials\Program.cs
/// g:\projektinterkosmos\interkosmos\codecontractstrials\codecontractstrials\SomeClass.cs
///
/// h:\vs2008\lab\decoratorversuch\decoratorversuch\Program.cs
///
/// i:\developer\vs2008\projects\demos\eigene\collectiveeventcontract\eineventvieleklassen\CollectiveEventArgs.cs
/// i:\developer\vs2008\projects\demos\eigene\collectiveeventcontract\eineventvieleklassen\CollectiveEventContract.cs
/// i:\developer\vs2008\projects\demos\eigene\collectiveeventcontract\eineventvieleklassen\Program.cs
///
/// Press any key to terminate the program.
/// */
/// ]]>
/// </code>
/// </example>
public sealed class ParallelFileSearcher
{
#region Delegates
/// <summary>
/// Kapselt eine Methode, die aufgerufen wird, wenn die gesuchte Datei gefunden wurde.
/// </summary>
public delegate void FoundFileHandler(string fullFileName);
/// <summary>
/// Kapselt eine Methode, die aufgerufen wird,
/// wenn versucht wurde, auf ein Verzeichnis zuzugreifen,
/// für das keine Zugriffsberechtigung besteht.
/// </summary>
public delegate void CurrentAccessDeniedHandler(string fullName);
#endregion
#region Events
/// <summary>
/// Tritt ein wenn die gesuchte Datei gefunden wurde.
/// </summary>
public event FoundFileHandler FoundFile;
/// <summary>
/// Tritt ein wenn für den Zugriff auf ein Verzeichnis oder eine Datei keine Berechtigung besteht.
/// </summary>
public event CurrentAccessDeniedHandler CallOutUnauthorizedAccess;
#endregion
#region Fields
private List<string> fileList = new List<string>();
private volatile string content;
private volatile bool found;
private FindMode mode;
private volatile string namePattern;
#endregion Fields
#region Constructors
/// <summary>
/// Initialisiert eine neue Instanz der <see cref="ParallelFileSearcher"/> Klasse.
/// </summary>
/// <param name="suppressExceptions">Wenn auf <c>true</c> gesetzt,
/// werden IO-Exceptions ignoriert.</param>
public ParallelFileSearcher(bool suppressExceptions)
{
SuppressExceptions = suppressExceptions;
}
#endregion Constructors
#region Properties
/// <summary>
/// Ruft einen Wert ab, der angibt ob Exceptions ignoriert werden.
/// </summary>
/// <value>
/// <c>true</c> wenn Exceptions ignoriert werden; anderenfalls <c>false</c>.
/// </value>
public bool SuppressExceptions { get; private set; }
#endregion Properties
#region Methods
#region Public Methods
/// <summary>
/// Findet Dateien und/oder bestimmten Inhalt von Dateien.
/// </summary>
/// <param name="searchSets">Eine Liste mit Suchsets (Instanzen der
/// <see cref="SearchSet"/>-Klasse.</param>
/// <param name="filenamePattern">Ein Dateinamensmuster (z.B. *.cs).</param>
/// <param name="contentToSearchFor">Der textuelle Inhalt, nach dem gesucht werden soll.</param>
/// <param name="findMode">Der durch die
/// <see cref="FindMode"/>-Enumeration angegebene Suchmodus.</param>
/// <returns>Eine Liste mit voll qualifizierten Dateinamen
/// (Instanzen der <see cref="FileInfo"/>-Klasse,
/// die den Suchkriterien entspricht.</returns>
/// <example>
/// <code>
/// <![CDATA[
/// using System;
/// using System.Collections.Generic;
/// using System.IO;
/// using DotNetExpansions.ParallelSearch;
///
/// namespace ParallelSearchDemo
/// {
/// class Program
/// {
/// public static void Main()
/// {
/// const bool ignoreExceptions = true;
/// var parallelFileSearcher = new ParallelFileSearcher(ignoreExceptions);
/// parallelFileSearcher.FoundFile += FileFoundHandler;
/// parallelFileSearcher.CallOutUnauthorizedAccess += ShowCurrentlyDeniedAccess;
///
/// // Make a container for the search sets.
/// List<SearchSet> searchSets = new List<SearchSet>();
///
/// // Generate a search set...
/// var searchSet = new SearchSet(
/// new DirectoryInfo(@"C:\System Volume Information"),
/// SearchOption.TopDirectoryOnly);
/// // ...and add it to the container.
/// searchSets.Add(searchSet);
///
/// // Generate another search set...
/// searchSet = new SearchSet(
/// new DirectoryInfo(@"I:\Developer\VS2008\Projects\DotNetExpansions\Demos"),
/// SearchOption.AllDirectories);
/// // ...and add it to the container.
/// searchSets.Add(searchSet);
///
/// // Define search-parameters.
/// string filenamePattern = "*.cs";
/// string contentToSearchFor = ""; // Could also be null.
///
/// // Start the search with those parameters.
/// Console.WriteLine("Search in progress. Please wait...");
/// List<FileInfo> fileInfos =
/// parallelFileSearcher.FindFiles(
/// searchSets, filenamePattern, contentToSearchFor, FindMode.FindAll);
/// // Do something with fileInfos like, for instance, delete those files.
/// }
///
/// private static void ShowCurrentlyDeniedAccess(string fullName)
/// {
/// Console.WriteLine("Access denied on " + fullName);
/// }
///
/// private static void FileFoundHandler(string fullFileName)
/// {
/// Console.WriteLine(fullFileName);
/// }
/// }
/// }]]>
/// </code>
/// </example>
public List<FileInfo> FindFiles(
List<SearchSet> searchSets, string filenamePattern,
string contentToSearchFor, FindMode findMode)
{
var permission = new FileIOPermission(PermissionState.Unrestricted);
permission.AllFiles = FileIOPermissionAccess.AllAccess;
SetInstanceParameters(filenamePattern, contentToSearchFor, findMode);
List<SearchSet> drivesAndFolders = GetDrivesAndFolders(searchSets);
IEnumerable<IGrouping<string, SearchSet>> fileGroups = GroupDriveItems(drivesAndFolders);
List<string> internalList = InvokeSearchBase(fileGroups);
var fileInfos = new List<FileInfo>();
foreach(var item in internalList)
{
fileInfos.Add(new FileInfo(item));
}
return fileInfos;
}
#endregion
#region Private methods
private static List<SearchSet> GetDrivesAndFolders(
IEnumerable<SearchSet> searchSets)
{
var drivesAndFolders = new List<SearchSet>();
foreach(var item in searchSets)
{
drivesAndFolders.Add(new SearchSet(item.DirectoryInformation, item.Recursive));
}
return drivesAndFolders;
}
private void GetFiles(IEnumerable<FileInfo> files)
{
// Wenn keine Content-Angabe vorhanden ist, soll der Inhalt der Files nicht durchsucht werden.
if(!string.IsNullOrEmpty(content))
{
SearchFileContents(files);
}
else
{
found = true;
foreach(var file in files)
{
fileList.Add(file.FullName);
if(FoundFile != null)
FoundFile(file.FullName);
}
}
}
private void SearchFileContents(IEnumerable<FileInfo> files)
{
foreach(var file in files)
{
StreamReader stream = null;
try
{
stream = file.OpenText();
string fileContent = stream.ReadToEnd();
if(fileContent.Contains(content))
{
found = true;
fileList.Add(file.FullName);
if(FoundFile != null)
FoundFile(file.FullName);
if(mode == FindMode.FindOne)
{
stream.Close();
stream.Dispose();
break;
}
}
}
catch(IOException)
{
if(!SuppressExceptions)
throw;
}
catch(UnauthorizedAccessException)
{
if(!SuppressExceptions)
throw;
if(CallOutUnauthorizedAccess != null)
CallOutUnauthorizedAccess(file.FullName);
}
finally
{
if(stream != null)
{
stream.Close();
stream.Dispose();
}
}
}
}
private void GetFileInfos(SearchSet container, IEnumerable<DirectoryInfo> directories)
{
foreach(var directory in directories)
{
try
{
FileInfo[] files = directory.GetFiles(namePattern, container.Recursive);
if(files.Length > 0)
GetFiles(files);
}
catch(UnauthorizedAccessException)
{
if(!SuppressExceptions)
throw;
if(CallOutUnauthorizedAccess != null)
CallOutUnauthorizedAccess(directory.FullName);
}
catch(IOException)
{
if(!SuppressExceptions)
throw;
}
}
}
private static IEnumerable<IGrouping<string, SearchSet>> GroupDriveItems(
IEnumerable<SearchSet> folders)
{
IEnumerable<IGrouping<string, SearchSet>> query =
folders.GroupBy(drive => drive.DirectoryInformation.Root.ToString(), container => container);
return query;
}
private void InvokeSearchByFileGroups(
IEnumerable<IGrouping<string, SearchSet>> fileGroups,
AutoResetEvent[] threadReadyEvents)
{
int counter = 0;
foreach(IGrouping<string, SearchSet> fileGroup in fileGroups)
{
threadReadyEvents[counter] = new AutoResetEvent(false);
IEnumerable<SearchSet> containers =
from items in fileGroup
select items;
object parameters =
new SearchTaskParameters(containers, threadReadyEvents[counter]);
if(!found)
ThreadPool.QueueUserWorkItem(Search, parameters);
counter++;
}
}
private List<string> InvokeSearchBase(
IEnumerable<IGrouping<string, SearchSet>> fileGroups)
{
var threadReadyEvents = new AutoResetEvent[fileGroups.Count()];
InvokeSearchByFileGroups(fileGroups, threadReadyEvents);
WaitForThreads(threadReadyEvents);
return fileList;
}
private void Search(object parameters)
{
if(found && mode == FindMode.FindOne)
return;
// Container auspacken -->>
IEnumerable<SearchSet> folderGroup;
AutoResetEvent doneEvent;
UnpackParameterContainer(parameters, out folderGroup, out doneEvent);
// <<--
// Schleife für Folder innerhalb eines Laufwerks.
foreach(SearchSet container in folderGroup)
{
var dir = new DirectoryInfo(container.DirectoryInformation.FullName);
if(!dir.Exists)
break;
dir.GetAccessControl();
var directories = new DirectoryInfo[] { };
try
{
directories = dir.GetDirectories();
}
catch(UnauthorizedAccessException)
{
if(!SuppressExceptions)
throw;
if(CallOutUnauthorizedAccess != null)
CallOutUnauthorizedAccess(container.DirectoryInformation.FullName);
}
GetFileInfos(container, directories);
}
doneEvent.Set();
}
private void SetInstanceParameters(
string filenamePattern, string contentToSearchFor, FindMode findMode)
{
if(string.IsNullOrEmpty(filenamePattern))
throw new ArgumentException("filenamePattern fehlt.");
namePattern = filenamePattern;
content = contentToSearchFor;
mode = findMode;
}
private static void UnpackParameterContainer(
object parameters, out IEnumerable<SearchSet> folderGroup,
out AutoResetEvent doneEvent)
{
folderGroup = ((SearchTaskParameters)parameters).Containers;
doneEvent = ((SearchTaskParameters)parameters).DoneEvent;
}
private void WaitForThreads(AutoResetEvent[] threadReadyEvents)
{
if(mode == FindMode.FindAll)
{
WaitHandle.WaitAll(threadReadyEvents);
threadReadyEvents = null;
}
else
{
WaitHandle.WaitAny(threadReadyEvents);
threadReadyEvents = null;
}
}
#endregion Private methods
#endregion Methods
}
}
//=========================================================
using System.IO;
namespace DotNetExpansions.ParallelSearch
{
/// <summary>
/// Stellt einen Suchset, bestehend aus dem zu durchsuchenden Pfad
/// und der Angabe, ob dieser Pfad rekursiv (inklusive Unterordnern) durchsucht werden soll.
/// </summary>
public sealed class SearchSet
{
#region Constructors
/// <summary>
/// Initialisiert eine neue Instanz der <see cref="SearchSet"/> Klasse.
/// </summary>
/// <param name="directoryInfo">Eine Pfadangabe in Form einer
/// <see cref="DirectoryInfo"/>-Instanz.</param>
/// <param name="recursive">Eine <see cref="SearchOption"/>-Enumeration,
/// die angibt ob der Pfad rekursiv durchsucht werden soll.</param>
public SearchSet(DirectoryInfo directoryInfo, SearchOption recursive)
{
DirectoryInformation = directoryInfo;
Recursive = recursive;
}
#endregion Constructors
#region Properties
/// <summary>
/// Ruft den aktuell zu durchsuchenden Pfad des Suchsets ab.
/// </summary>
/// <value>Eine Instanz der <see cref="DirectoryInfo"/>-Klasse.</value>
public DirectoryInfo DirectoryInformation { get; private set; }
/// <summary>
/// Ruft die Suchoption des aktuellen Suchsets ab.
/// </summary>
/// <value>Eine der Enumerationen von <see cref="SearchOption"/>.</value>
public SearchOption Recursive { get; private set; }
#endregion Properties
}
}
//=========================================================
using System.Collections.Generic;
using System.Threading;
namespace DotNetExpansions.ParallelSearch
{
/// <summary>
/// Beinhaltet Parameter, die an die Suchthreads übegeben werden.
/// <remarks>
/// Eine Methode die über den Threadpool gestartet wird,
/// darf nur einen Parameter vom Typ Object haben.
/// Mittels der ParameterContainer-Klasse wird diese Klippe elegant umschifft.
/// </remarks>
/// </summary>
internal class SearchTaskParameters
{
#region Constructors
/// <summary>
/// Initialisiert eine neue Instanz der <see cref="SearchTaskParameters"/>-Klasse.
/// </summary>
/// <param name="containers">SearchSets</param>
/// <param name="doneEvent">Jeder Thread bekommt ein
/// <see cref="AutoResetEvent"/> in's Gepäck.</param>
internal SearchTaskParameters(
IEnumerable<SearchSet> containers, AutoResetEvent doneEvent)
{
Containers = containers;
DoneEvent = doneEvent;
}
#endregion Constructors
#region Properties
internal AutoResetEvent DoneEvent { get; private set; }
internal IEnumerable<SearchSet> Containers { get; private set; }
#endregion Properties
}
}
|