-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
245 lines (214 loc) · 7.5 KB
/
Program.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
using System.Text;
using System.Diagnostics;
using System.Collections.Concurrent;
class Program
{
static void Main()
{
string folderToSearch = GetInput("Enter the folder to search: ", Directory.GetCurrentDirectory());
while (!Directory.Exists(folderToSearch))
{
Console.WriteLine("Invalid folder path. Please try again.");
folderToSearch = GetInput("Enter the folder to search: ", Directory.GetCurrentDirectory());
}
string searchTerm = GetInput("Enter the string to search: ", "Hello World!");
string caseSensitiveInput = GetInput("Case-sensitive search? (yes/no): ", "no").ToLower();
bool isCaseSensitive = caseSensitiveInput.StartsWith('y');
string countFilesInput = GetInput("Count files before scanning? (yes/no): ", "yes").ToLower();
bool countFiles = countFilesInput.StartsWith('y');
string openOnFoundInput = GetInput("Open location on found files? (yes/no): ", "no").ToLower();
bool openOnFound = openOnFoundInput.StartsWith('y');
if (!Directory.Exists(folderToSearch))
{
Console.WriteLine("Invalid folder path. Please try again.");
return;
}
SearchStringInFiles(folderToSearch, searchTerm, countFiles, openOnFound, isCaseSensitive);
}
static string GetInput(string prompt, string defaultValue)
{
Console.Write(prompt);
string? input = Console.ReadLine()?.Trim();
if (string.IsNullOrEmpty(input))
{
input = defaultValue;
Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.WriteLine(prompt + input);
}
return input;
}
static void SearchStringInFiles(string folder, string searchString, bool countFiles, bool openOnFound, bool isCaseSensitive)
{
ConcurrentBag<string> foundFiles = new();
int scannedFiles = 0;
int totalFiles = 0;
if (countFiles)
{
try
{
totalFiles = EnumerateFilesSafe(folder).Count();
Console.WriteLine($"Total files to scan: {totalFiles}");
}
catch (Exception e)
{
Console.WriteLine($"Error during file count: {e.Message}");
}
}
else
{
Console.WriteLine("Skipping file count. Scanning directly...");
}
//Stopwatch stopwatch = Stopwatch.StartNew();
Parallel.ForEach(
EnumerateFilesSafe(folder),
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
file =>
{
try
{
if (IsUtf8File(file) && FileContainsString(file, searchString, isCaseSensitive))
{
foundFiles.Add(file);
if (openOnFound)
{
Process.Start("explorer.exe", $"/select,\"{file}\"");
}
}
}
catch (Exception e)
{
Console.WriteLine($"Error processing file {file}: {e.Message}");
}
int currentScanned = Interlocked.Increment(ref scannedFiles);
if (countFiles)
Console.WriteLine($"Scanned {currentScanned}/{totalFiles}: {file}");
else
Console.WriteLine($"Scanned {currentScanned}: {file}");
});
//stopwatch.Stop();
//Console.WriteLine($"Execution Time: {stopwatch.ElapsedMilliseconds} ms");
File.WriteAllText("found.log", string.Empty);
if (foundFiles.Count > 0)
{
Console.WriteLine("\nFound files:");
using (StreamWriter log = new StreamWriter("found.log", false))
{
foreach (string foundFile in foundFiles)
{
Console.WriteLine(foundFile);
log.WriteLine(foundFile);
}
}
Console.WriteLine($"\nLogged found files at {Path.GetFullPath("found.log")}");
}
else
{
Console.WriteLine("\nNo files found containing the search term.");
}
Console.WriteLine($"\nTotal files scanned: {scannedFiles}");
Console.WriteLine($"Total files found: {foundFiles.Count}");
Console.WriteLine("Press Enter to exit...");
Console.ReadLine();
}
static IEnumerable<string> EnumerateFilesSafe(string path)
{
Stack<string> dirs = new();
List<string> files = new();
dirs.Push(path);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
try
{
files.AddRange(Directory.EnumerateFiles(currentDir));
foreach (var subDir in Directory.EnumerateDirectories(currentDir))
{
dirs.Push(subDir);
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine($"Access denied to: {currentDir}");
}
}
return files;
}
static bool FileContainsString(string filePath, string searchString, bool isCaseSensitive)
{
try
{
using var reader = new StreamReader(filePath, Encoding.UTF8, true, bufferSize: 4096);
string line;
while ((line = reader.ReadLine()) != null)
{
if (isCaseSensitive)
{
if (line.Contains(searchString, StringComparison.Ordinal))
return true;
}
else
{
if (line.Contains(searchString, StringComparison.OrdinalIgnoreCase))
return true;
}
}
}
catch { }
return false;
}
static bool IsUtf8File(string filePath)
{
try
{
using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
if (!IsValidUtf8(buffer, bytesRead))
return false;
}
return true;
}
catch
{
return false;
}
}
static bool IsValidUtf8(byte[] bytes, int length)
{
int i = 0;
while (i < length)
{
byte b = bytes[i];
if (b <= 0x7F)
{
i++;
continue;
}
else if ((b & 0xE0) == 0xC0)
{
if (i + 1 >= length || (bytes[i + 1] & 0xC0) != 0x80)
return false;
i += 2;
}
else if ((b & 0xF0) == 0xE0)
{
if (i + 2 >= length || (bytes[i + 1] & 0xC0) != 0x80 || (bytes[i + 2] & 0xC0) != 0x80)
return false;
i += 3;
}
else if ((b & 0xF8) == 0xF0)
{
if (i + 3 >= length || (bytes[i + 1] & 0xC0) != 0x80 || (bytes[i + 2] & 0xC0) != 0x80 || (bytes[i + 3] & 0xC0) != 0x80)
return false;
i += 4;
}
else
{
return false;
}
}
return true;
}
}