-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
551 lines (460 loc) · 18.4 KB
/
Copy pathProgram.cs
File metadata and controls
551 lines (460 loc) · 18.4 KB
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
#region License
//------------------------------------------------------------------------------
// Copyright (c) Dmitrii Evdokimov
// Source https://github.com/diev/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//------------------------------------------------------------------------------
#endregion
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Xml.Linq;
namespace ACL2readonly
{
//:: Установка прав на архив
//icacls "path" /deny "principal":(DE) /t /c
internal class Program
{
//counters
private static int _totalDirs = 0;
private static int _totalFiles = 0;
private static int _newDirs = 0;
private static int _newFiles = 0;
private static int _renDirs = 0;
private static int _renFiles = 0;
private static int _renDirsE = 0;
private static int _renFilesE = 0;
private static int _level = 0;
private static int _maxLevel = 0;
private static int _errors = 0;
//app.config
private static readonly string _path = ConfigurationManager.AppSettings["Path"];
private static readonly string _deny = ConfigurationManager.AppSettings["Deny"];
private static string _log = ConfigurationManager.AppSettings["Log"];
private static string _logE;
//deny rights
private static readonly FileSystemRights _dirDeny = FileSystemRights.Delete | FileSystemRights.DeleteSubdirectoriesAndFiles;
private static readonly FileSystemRights _fileDeny = FileSystemRights.Delete | FileSystemRights.Write;
//cut basepath
private static readonly int _cut = _path.LastIndexOf(Path.DirectorySeparatorChar) + 1;
//switch logic
private static readonly bool _doRights = !string.IsNullOrEmpty(_deny);
private static void Main(string[] args)
{
//try
{
Console.WriteLine(Banner());
var logs = Directory.CreateDirectory(Path.Combine(_log, $"{DateTime.Now:yyyy}"));
_log = Path.Combine(logs.FullName, $"{DateTime.Now:yyyyMMdd}.log");
_logE = Path.Combine(logs.FullName, $"{DateTime.Now:yyyyMMdd}.err");
if (!Directory.Exists(_path))
{
Console.WriteLine($"Path \"{_path}\" not exists!");
Environment.Exit(2);
}
var watch = Stopwatch.StartNew();
Console.WriteLine("Wait...");
File.AppendAllText(_log, $"[{DateTime.Now:yyyy-MM-dd HH:mm}]\n");
ProcessDir(_path);
watch.Stop();
StringBuilder report = new StringBuilder();
report.AppendLine($"Execution Time: {watch.ElapsedMilliseconds} ms.");
report.Append("Total: ");
report.Append($"{_totalDirs} folders (+{_newDirs}, ren {_renDirs}/E{_renDirsE}), ");
report.Append($"{_totalFiles} files (+{_newFiles}, ren {_renFiles}/E{_renFilesE}), ");
report.Append($"{_maxLevel} levels, ");
report.Append($"{_errors} errors");
if (_errors > 0)
{
report.Append($" (see \"{_logE}\")");
}
report.AppendLine(".");
string s = report.ToString();
Console.WriteLine($"\n{s}");
File.AppendAllText(_log, $"{s}\n");
Environment.Exit(0);
}
//catch (Exception e)
//{
// Console.WriteLine(e.Message);
// File.AppendAllText(_logE, $"{e}\n\n");
// Environment.Exit(1);
//}
}
/// <summary>
/// Returns a banner text for this application.
/// </summary>
/// <returns>String of text.</returns>
private static string Banner()
{
var assembly = Assembly.GetCallingAssembly();
var assemblyName = assembly.GetName();
var name = assemblyName.Name;
var version = assemblyName.Version; // Major.Minor.Build.Revision
string build = (version.Revision > 0) ? $" build {version.Revision}" : "";
var ver = version.ToString(3);
var d = Attribute.GetCustomAttribute(assembly, typeof(AssemblyDescriptionAttribute)) as AssemblyDescriptionAttribute;
var c = Attribute.GetCustomAttribute(assembly, typeof(AssemblyCopyrightAttribute)) as AssemblyCopyrightAttribute;
string C = c.Copyright.Replace("\u00a9", "(c)");
return $"{name} v{ver}{build} - {d.Description}\n{C}\n";
}
/// <summary>
/// Processes a specified directory.
/// </summary>
/// <param name="file">Directory name.</param>
private static void ProcessDir(string dir)
{
_totalDirs++;
if (_level > _maxLevel)
{
_maxLevel = _level;
}
string sdir = dir.Substring(_cut) + Path.DirectorySeparatorChar;
string d1 = Path.GetFileName(dir);
string d2 = d1.Trim();
bool safe = true;
while (d2.Contains(".."))
{
d2 = d2.Replace("..", ".");
}
while (d2.Contains(" ."))
{
d2 = d2.Replace(" .", ".");
}
while (d2.Contains(" ,"))
{
d2 = d2.Replace(" ,", ",");
}
while (d2.Contains("( "))
{
d2 = d2.Replace("( ", "(");
}
while (d2.Contains(" )"))
{
d2 = d2.Replace(" )", ")");
}
while (d2.Contains(" "))
{
d2 = d2.Replace(" ", " ");
}
while (d2.EndsWith("."))
{
d2 = d2.Substring(0, d2.Length - 1);
safe = false;
}
if (!d2.Equals(d1))
{
string dir2 = Path.Combine(Path.GetDirectoryName(dir), d2);
if (Directory.Exists(dir2))
{
_renDirsE++;
File.AppendAllText(_logE, $"D2! \"{sdir}\"\n");
d2 = GetFreeDirname(d2);
dir2 = Path.Combine(Path.GetDirectoryName(dir), d2);
}
_renDirs++;
File.AppendAllText(_log, $"ren \"{sdir}\" \"{d2}\"\n");
if (safe)
{
Directory.Move(dir, dir2);
}
else if (!RenameDirectoryWithSideWhiteSpaces(dir, dir2))
{
_renDirsE++;
File.AppendAllText(_logE, $"DX! \"{sdir}\"\n");
return; //TODO bad dir!
}
dir = dir2;
sdir = dir.Substring(_cut) + Path.DirectorySeparatorChar;
//_renDirsE++;
//File.AppendAllText(_logE, $"D1! \"{sdir}\"\n");
}
if (_doRights)
{
DirectorySecurity dirSecurity;
try
{
if (_doRights)
{
dirSecurity = Directory.GetAccessControl(dir);
if (NewEntry(dirSecurity))
{
_newDirs++;
dirSecurity.AddAccessRule(new FileSystemAccessRule(_deny, _dirDeny, AccessControlType.Deny));
Directory.SetAccessControl(dir, dirSecurity);
Console.WriteLine(sdir);
File.AppendAllText(_log, $"{sdir}\n");
}
}
}
catch (ArgumentException)
{
_errors++;
Console.WriteLine("Error dirname! " + sdir);
File.AppendAllText(_logE, $"Error dirname! \"{sdir}\"\n");
}
catch (DirectoryNotFoundException)
{
_errors++;
Console.WriteLine("Error dirname_! " + sdir);
File.AppendAllText(_logE, $"Error dirname_! \"{sdir}\"\n");
}
catch (Exception e)
{
_errors++;
Console.WriteLine("Error dir! " + sdir);
File.AppendAllText(_logE, $"Error dir! \"{sdir}\"\n{e}\n\n");
}
}
var files = Directory.EnumerateFiles(dir);
foreach (string file in files)
{
ProcessFile(file);
}
_level++;
var subdirs = Directory.EnumerateDirectories(dir);
foreach (string subdir in subdirs)
{
ProcessDir(subdir);
}
_level--;
}
/// <summary>
/// Processes a specified file.
/// </summary>
/// <param name="file">Filename.</param>
private static void ProcessFile(string file)
{
_totalFiles++;
string sfile = file.Substring(_cut);
string f1 = Path.GetFileName(file);
string f2 = f1.Trim();
while (f2.Contains(".."))
{
f2 = f2.Replace("..", ".");
}
while (f2.Contains(" ."))
{
f2 = f2.Replace(" .", ".");
}
while (f2.Contains(" ,"))
{
f2 = f2.Replace(" ,", ",");
}
while (f2.Contains("( "))
{
f2 = f2.Replace("( ", "(");
}
while (f2.Contains(" )"))
{
f2 = f2.Replace(" )", ")");
}
while (f2.Contains(" "))
{
f2 = f2.Replace(" ", " ");
}
if (!f2.Equals(f1))
{
string file2 = Path.Combine(Path.GetDirectoryName(file), f2);
try
{
if (File.Exists(file2))
{
if (FileHashesEqual(file, file2))
{
_renFiles++;
File.AppendAllText(_log, $"ren(h) \"{sfile}\"\n");
File.Delete(file2);
File.Move(file, file2);
file = file2;
sfile = file.Substring(_cut);
}
else
{
//_renFilesE++;
//File.AppendAllText(_logE, $"F2! \"{sfile}\"\n");
_renFiles++;
File.AppendAllText(_log, $"ren(n) \"{sfile}\"\n");
file2 = GetFreeFilename(file2);
File.Move(file, file2);
file = file2;
sfile = file.Substring(_cut);
}
}
else
{
_renFiles++;
//File.AppendAllText(_log, $"ren \"{sfile}\"\n");
File.Move(file, file2);
file = file2;
sfile = file.Substring(_cut);
}
}
catch (Exception)
{
File.AppendAllText(_log, $"use \"{sfile}\"\n");
}
}
if (_doRights)
{
FileSecurity fileSecurity;
try
{
fileSecurity = File.GetAccessControl(file);
if (NewEntry(fileSecurity))
{
_newFiles++;
fileSecurity.AddAccessRule(new FileSystemAccessRule(_deny, _fileDeny, AccessControlType.Deny));
File.SetAccessControl(file, fileSecurity);
Console.WriteLine(sfile);
File.AppendAllText(_log, $"{sfile}\n");
}
}
catch (ArgumentException)
{
_errors++;
Console.WriteLine("Error filename! " + sfile);
File.AppendAllText(_logE, $"Error filename! \"{sfile}\"\n");
}
catch (Exception e)
{
_errors++;
Console.WriteLine("Error file! " + sfile);
File.AppendAllText(_logE, $"Error file! \"{sfile}\"\n{e}\n\n");
}
}
}
/// <summary>
/// Check if a new directory requires to change rights.
/// </summary>
/// <param name="security"></param>
/// <returns>True if this directory requires.</returns>
private static bool NewEntry(in DirectorySecurity security)
{
var rules = security.GetAccessRules(true, true, typeof(NTAccount));
foreach (FileSystemAccessRule rule in rules)
{
if (rule.AccessControlType.HasFlag(AccessControlType.Deny) &&
rule.IdentityReference.Value.Equals(_deny, StringComparison.OrdinalIgnoreCase) &&
rule.FileSystemRights.HasFlag(_dirDeny))
{
return false;
}
}
return true;
}
/// <summary>
/// Check if a new file requires to change rights.
/// </summary>
/// <param name="security"></param>
/// <returns>True if this file requires.</returns>
private static bool NewEntry(in FileSecurity security)
{
var rules = security.GetAccessRules(true, true, typeof(NTAccount));
foreach (FileSystemAccessRule rule in rules)
{
if (rule.AccessControlType.HasFlag(AccessControlType.Deny) &&
rule.IdentityReference.Value.Equals(_deny, StringComparison.OrdinalIgnoreCase) &&
rule.FileSystemRights.HasFlag(_fileDeny))
{
return false;
}
}
return true;
}
/// <summary>
/// Compares contents of two files if they are equal.
/// </summary>
/// <param name="file1">Filename 1.</param>
/// <param name="file2">Filename 2.</param>
/// <returns>True if contents are equal.</returns>
private static bool FileHashesEqual(string file1, string file2)
{
byte[] hash1, hash2;
using (var hasher = MD5.Create())
{
using (var stream = File.OpenRead(file1))
{
hash1 = hasher.ComputeHash(stream);
}
using (var stream = File.OpenRead(file2))
{
hash2 = hasher.ComputeHash(stream);
}
}
return hash1.Equals(hash2);
}
/// <summary>
/// Looks for a free dirname with (++counter) if there is same used.
/// </summary>
/// <param name="file">Dirname to look.</param>
/// <returns>New unused dirname.</returns>
private static string GetFreeDirname(string dir)
{
string ext = Path.GetExtension(dir);
string name = Path.ChangeExtension(dir, null);
int n = 1;
while (Directory.Exists($"{name} ({++n}){ext}"))
{
}
return $"{name} ({n}){ext}";
}
/// <summary>
/// Looks for a free filename with (++counter) if there is same used.
/// </summary>
/// <param name="file">Filename to look.</param>
/// <returns>New unused filename.</returns>
private static string GetFreeFilename(string file)
{
string ext = Path.GetExtension(file);
string name = Path.ChangeExtension(file, null);
int n = 1;
while (File.Exists($"{name} ({++n}){ext}"))
{
}
return $"{name} ({n}){ext}";
}
// https://social.msdn.microsoft.com/Forums/en-US/92f8813f-5dbf-4e67-b8eb-2c91de2a6696/directorynotfoundexception-when-directory-name-ends-with-white-space?forum=csharpgeneral
[DllImport("kernel32.dll", EntryPoint = "MoveFileW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool MoveFile(string lpExistingFileName, string lpNewFileName);
private static bool RenameDirectoryWithSideWhiteSpaces(string path, string newPath)
{
var oldPath = path.StartsWith(@"\\?\") ? path : @"\\?\" + path;
var result = MoveFile(oldPath, newPath);
return result;
}
private static string RemoveSideWhiteSpaces(string path)
{
//var parent = Path.GetDirectoryName(path);
//var name = Path.GetFileName(path);
//var result = Path.Combine(parent ?? Path.GetPathRoot(path), name.Trim());
var breadcrumbs = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).Select(x => x.Trim()).ToArray();
for (int i = 0; i < breadcrumbs.Length; i++)
{
while (breadcrumbs[i].EndsWith("."))
{
breadcrumbs[i] = breadcrumbs[i].Substring(0, breadcrumbs[i].Length - 1);
}
}
var result = string.Join(@"\", breadcrumbs);
return result;
}
}
}