-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
1348 lines (1139 loc) · 50.6 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
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Виноградов Сергей Васильевич, 1984, Мытищи
// https://github.com/VinnySmallUtilities/sdel
// 2022-2024 год
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
namespace sdel
{
class MainClass
{
class Progress
{
public long rewritedSize = 0;
public long SizeToRewrite = 0;
public long rewritedCnt = 0;
public long cntToRewrite = 0;
/// <summary>Выводить прогресс (pr)</summary>
public int showProgressFlag = 0; /// <summary>Замедлять работу программы, вставляя паузы (sl)</summary>
public int slowDownFlag = 0; /// <summary>Вместо перезатирания существующих файлов создать большой файл для перезатирания пустого пространства на диске (cr)</summary>
public int createDirectories = 0;
/// <summary>Создание файла с последующим удалением без перезатирания (crs)</summary>
public int createWithSimpleDeleting = 0; /// <summary>Создавать только директории, не создавая большого файла (crf)</summary>
public int createDirectoriesOnly = 0;
/// <summary>Не удалять директории (только файлы, оставить структуру папок нетронутой)</summary>
public int doNotDeleteDirectories = 0; /// <summary>Не удалять файлы (для перезатирания ssd)</summary>
public int doNotDeleteFiles = 0;
public DateTime lastMessage = DateTime.MinValue;
public DateTime creationTime = DateTime.Now;
/// <summary>Создаёт объект, отображающий прогресс выполнения</summary>
/// <param name="SizeToRewrite">Общий размер файлов для перезаписи</param>
/// <param name="cntToRewrite">Количество файлов для перезаписи</param>
/// <param name="showProgressFlag">Флаг прогресса. 1 - отображать прогресс выполнения в консоли</param>
public Progress(long SizeToRewrite = 0, long cntToRewrite = 0, int showProgressFlag = 1, Progress? progress = null)
{
if (progress is not null)
{
this.SizeToRewrite = progress.SizeToRewrite;
this.cntToRewrite = progress.cntToRewrite;
this.showProgressFlag = progress.showProgressFlag;
this.slowDownFlag = progress.slowDownFlag;
this.createWithSimpleDeleting = progress.createWithSimpleDeleting;
this.createDirectoriesOnly = progress.createDirectoriesOnly;
this.doNotDeleteDirectories = progress.doNotDeleteDirectories;
this.doNotDeleteFiles = progress.doNotDeleteFiles;
this.creationTime = progress.creationTime;
}
if (SizeToRewrite > 0 || progress is null)
this.SizeToRewrite = SizeToRewrite;
if (cntToRewrite > 0 || progress is null)
this.cntToRewrite = cntToRewrite;
if (progress is null)
this.showProgressFlag = showProgressFlag;
}
public float progress
{
get
{
if (cntToRewrite <= 1)
if (SizeToRewrite > 0)
return (rewritedSize / (float) SizeToRewrite) * 100f;
else
return 100f;
var cntProgress = rewritedCnt / (float) (cntToRewrite - 1f);
var sizeProgress = SizeToRewrite == 0 ? 1f : rewritedSize / (float) SizeToRewrite;
if (cntProgress > 1f)
cntProgress = 1f;
if (sizeProgress > 1f)
sizeProgress = 1f;
// Преобразуем в проценты и находим среднее арифметическое между прогрессом по количеству файлов и прогрессом по количеству байтов
return (cntProgress + sizeProgress) * 50f;
}
}
public string progressStr => progress.ToString("F2") + "% ";
public uint IntervalToMessageInSeconds = 1;
public void showMessage(string endOfMsg = "", bool notPrintProgress = false, bool forced = false)
{
if (showProgressFlag == 0)
return;
var now = DateTime.Now;
if (!forced && (now - lastMessage).TotalSeconds < IntervalToMessageInSeconds)
return;
lastMessage = now;
Console.CursorLeft = 0;
Console.ForegroundColor = ConsoleColor.Green;
if (notPrintProgress)
Console.Write(endOfMsg);
else
Console.Write(progressStr + " " + endOfMsg);
Console.ResetColor();
Console.CursorVisible = false;
}
public string getMessageForEntireTimeOfSanitization
{
get
{
var ts = DateTime.Now - creationTime;
return ts.ToString();
}
}
}
const int BufferSize = 16 * 1024 * 1024;
const int MinTimeToSleepInMs = 50;
public static int Main(string[] args)
{
#if DEBUG
// args = new string[] { "v", "/home/g2/g2/.wine/" };
// args = new string[] { "z3", "/inRam/1.txt" };
// args = new string[] { "vvslpr", "/inRam/1/" };
// args = new string[] { "-", "/inRam/Renpy/" };
// args = new string[] { "vvprsl", "/Arcs/toErase" };
// args = new string[] { "vvpr", "/Arcs/toErase" };
// args = new string[] { "vv_pr_crds", "/inRam/1" };
// args = new string[] { "vv_pr_crf", "/inRam/1" };
// args = new string[] { "'v pr crf'", "/home/vinny/_toErase" };
// args = new string[] { "'v pr crds'", "/inRam/rcd/_toErase" };
// args = new string[] { "'v pr crs'", "/media/vinny/0A36-9B56/System Volume Information/_toErase" };
// args = new string[] { "'v pr crs'" };
// args = new string[] { ":prv" };
#endif
int returnCode = -1;
try
{
returnCode = Main_OneArgument(args);
// if (returnCode != 0)
if (returnCode == 101 || returnCode == 102)
return returnCode;
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("ERROR: " + ex.Message + "\n" + ex.StackTrace + "\n\n\n");
Console.ResetColor();
}
// sdel prv * добавляет новые параметры в конец
if (args.LongLength > 2)
for (long i = 2; i < args.LongLength; i++)
{
var line = args[i];
Console.WriteLine("\n--------------------------------\n");
Console.WriteLine("Try to re-executing with additional files");
try
{
var rc = Main_OneArgument( new string[] { args[0], line } );
if (rc != 0 && returnCode == 0)
returnCode = rc;
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("ERROR: " + ex.Message + "\n" + ex.StackTrace + "\n\n\n");
Console.ResetColor();
}
}
if (returnCode != 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("Error occured");
Console.ResetColor();
}
return returnCode;
}
public static int Main_OneArgument(string[] args)
// public static int Main(string[] args)
{
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Idle;
Console.CursorVisible = true;
if (args.Length == 1 && args[0].Contains(":"))
{
var stdIn = Console.OpenStandardInput();
using var stdR = new StreamReader(stdIn);
var ec = ExecuteSdels(args[0], stdR);
Console.CursorVisible = true;
return ec;
}
bool isFirstFileError = false;
if (args.Length > 0)
{
isFirstFileError = File.Exists(args[0]) || Directory.Exists(args[0]);
}
if (args.Length < 2 || isFirstFileError)
{
Console.WriteLine("sdel version: 2024 feb 28.21");
Console.Error.WriteLine("sdel 'flags' dir");
Console.WriteLine("Examples:");
Console.WriteLine("sdel - /home/user/.wine");
Console.WriteLine("sdel v /home/user/.wine");
Console.WriteLine("flag 'v' switches to verbosive mode");
Console.WriteLine("flag 'vv' switches to twice verbosive mode");
Console.WriteLine("flag 'z' switches to 0x00 pattern");
Console.WriteLine("flag 'z2' switches to twice rewriting. 0x55AA and 0x00 patterns");
Console.WriteLine("flag 'z3' switches to three rewriting. 0xCCCC, 0x6666, 0x00 patterns");
Console.WriteLine("flag 'pr' show progress");
Console.WriteLine("flag 'sl' get slow down progress (pauses when using the disk)");
Console.WriteLine("flag 'cr' set to creation mode. A not existence file must be created as big as possible");
Console.WriteLine("flag 'crd' set to creation mode with create a many count of directories");
Console.WriteLine("flag 'crds' or 'crs' set to the creation mode with a one time to write at the creation file moment");
Console.WriteLine("flag 'crf' set to the creation mode for create directories only");
Console.WriteLine("use ':' to use with conveyor. Example: ls -1 | sdel 'v:-'");
Console.WriteLine("ndd - do not delete directories");
Console.WriteLine("_ndf - do not delete files");
Console.WriteLine("Example:");
Console.WriteLine("sdel vvz2pr /home/user/.wine");
Console.WriteLine("sdel vv_z2_pr /home/user/.wine");
Console.WriteLine("sdel 'vv z2 pr' /home/user/.wine");
Console.WriteLine("sdel \"vv z2 pr\" /home/user/.wine");
Console.WriteLine("for SSD and flash");
Console.WriteLine("sdel 'crd pr v sl' ~/_toErase");
Console.WriteLine("for magnetic disks");
Console.WriteLine("sdel 'crds pr v sl' ~/_toErase");
Console.WriteLine("for file");
Console.WriteLine("sdel 'pr v' ~/_toErase");
Console.WriteLine("for directory");
Console.WriteLine("sdel 'pr v sl' ~/_toErase");
Console.WriteLine("for delete all logs in the Linux /var/log");
Console.WriteLine("sudo sdel ndd /var/log");
return 101;
}
Progress progress = new Progress(showProgressFlag: 0);
var path0 = args[1];
var path = Path.GetFullPath(path0); // new FileInfo(path0).FullName;
var flags = args[0];
int verbose = GetVerboseFlag(flags);
var zFlag = flags.Contains("z") ? 1 : 0;
if (flags.Contains("z2"))
{
zFlag = 2;
if (verbose > 0)
Console.WriteLine("z2: double rewrite: 0x55AA and 0x0000");
}
else
if (flags.Contains("z3"))
{
zFlag = 3;
if (verbose > 0)
Console.WriteLine("z3: triple rewrite: 0xCCCC 0x6666 0x00");
}
if (flags.Contains("ndd"))
{
progress.doNotDeleteDirectories = 1;
Console.WriteLine("ndd - do not delete directories");
}
if (flags.Contains("_ndf"))
{
progress.doNotDeleteFiles = 1;
progress.doNotDeleteDirectories = 1;
Console.WriteLine("_ndf - do not delete files");
}
var creationMode = flags.Contains("cr");
if (creationMode)
{
if (verbose > 0)
Console.WriteLine("cr* - creation mode");
if (flags.Contains("sl"))
{
progress.slowDownFlag = 1;
Console.WriteLine("sl - slow down");
}
if (flags.Contains("pr"))
progress.showProgressFlag = 1;
if (flags.Contains("crd") || flags.Contains("crsd"))
progress.createDirectories = 1;
if (flags.Contains("crs") || flags.Contains("crds") || flags.Contains("crsd"))
{
progress.createWithSimpleDeleting = 1;
Console.WriteLine("cr?s - creation mode without the file wiping (only create and fill)");
}
if (flags.Contains("crf"))
{
progress.createDirectories = 1;
progress.createDirectoriesOnly = 1;
if (verbose > 0)
Console.WriteLine($"crf - Only directories created, no have big file");
}
if (!createFile(path, progress: progress, verbose: verbose))
{
Console.CursorVisible = true;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"File creation failed with name '{path}'");
Console.ResetColor();
return 111;
}
if (progress.createWithSimpleDeleting > 0)
{
if (progress.doNotDeleteDirectories == 0)
{
if (verbose > 0)
Console.WriteLine($"Usually directory deleting (without additional rewriting)");
Directory.Delete(path, true);
Console.WriteLine($"Program ended with time {progress.getMessageForEntireTimeOfSanitization}. Deletion successfull ended for directory '{path}'");
}
else
Console.WriteLine($"Program ended with time {progress.getMessageForEntireTimeOfSanitization}. Creation successfull ended for directory '{path}'");
Console.CursorVisible = true;
return 0;
}
}
if (path0.StartsWith("'") || path0.StartsWith("\""))
{
if (!Directory.Exists(path) && !File.Exists(path))
{
path0 = path0.Substring(1, path0.Length - 2);
path = Path .GetFullPath(path0);
}
}
var isDirectory = false;
if (Directory.Exists(path))
{
isDirectory = true;
Console.WriteLine($"Directory to deletion: \"{path}\"");
}
else
if (!File.Exists(path))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Error.WriteLine($"File not exists:\n\"{path}\"");
Console.ResetColor();
Console.CursorVisible = true;
return 102;
}
else
{
Console.WriteLine($"File to deletion: \"{path}\"");
}
List<byte[]> bt = new List<byte[]>(4);
if (zFlag > 1)
{
if (zFlag >= 3)
{
ArrayInitialization(bt, 0xCC); // Это первое перезатирание при тройном перезатирании
}
ArrayInitialization(bt, 0x66);
}
var bt1 = new byte[BufferSize];
var A = new byte[] { 0x55, 0xAA };
for (int i = 0; i < bt1.Length; i++)
{
if (zFlag == 0)
bt1[i] = A[i & 1];
else
bt1[i] = 0; // Флаг z установлен - последнее перезатирание - 0
}
bt.Add(bt1);
if (!isDirectory)
{
var fi = new FileInfo(path);
if (flags.Contains("pr"))
{
var dt = progress.creationTime;
progress = new Progress(SizeToRewrite: fi.Length, cntToRewrite: 1, progress: progress) { showProgressFlag = 1 };
progress.creationTime = dt;
}
if (flags.Contains("sl"))
{
progress.slowDownFlag = 1;
Console.WriteLine("sl - slow down");
}
deleteFile(fi, bt, progress: progress, true, true, verbose: verbose);
progress.showMessage(forced: true);
if (File.Exists(path))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Program ended with time {progress.getMessageForEntireTimeOfSanitization}. Deletion failed for file '{path}'");
Console.ResetColor();
Console.CursorVisible = true;
return 15;
}
Console.WriteLine($"Program ended with time {progress.getMessageForEntireTimeOfSanitization}. Deletion successfull ended for file '{path}'");
Console.CursorVisible = true;
return 0;
}
if (verbose >= 1)
{
Console.WriteLine("Prepare a list of files to data sanitization");
}
if (flags.Contains("sl"))
{
progress.slowDownFlag = 1;
Console.WriteLine("sl - slow down");
}
if (flags.Contains("ndd"))
{
progress.doNotDeleteDirectories = 1;
Console.WriteLine("ndd - do not delete directories");
}
if (flags.Contains("_ndf"))
{
progress.doNotDeleteFiles = 1;
progress.doNotDeleteDirectories = 1;
Console.WriteLine("_ndf - do not delete files");
}
var di = new DirectoryInfo(path);
try
{
if (flags.Contains("pr"))
{
// var list = di.GetFiles("*", SearchOption.AllDirectories);
var list = di.EnumerateFiles("*", SearchOption.AllDirectories);
var dt = progress.creationTime;
progress = new Progress(progress: progress) { showProgressFlag = 1 };
progress.creationTime = dt;
foreach (var file in list)
{
try
{
progress.cntToRewrite += 1;
progress.SizeToRewrite += file.Length;
}
catch
{}
}
if (zFlag >= 2)
progress.SizeToRewrite *= zFlag;
if (zFlag >= 4)
throw new NotImplementedException();
var dirList = di.EnumerateDirectories("*", SearchOption.AllDirectories);
foreach (var file in list)
{
progress.cntToRewrite += 1;
}
}
}
catch (Exception e)
{
Console.Error.WriteLine($"Error for calculate progress for '{di.FullName}'\n{e.Message}\n{e.StackTrace}");
}
DeleteFilesFromDir(di, bt: bt, progress: progress, verbose: verbose);
if (progress.doNotDeleteFiles != 0)
{
progress.showMessage(forced: true);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine($"Program ended with time {progress.getMessageForEntireTimeOfSanitization}. Sanitization successfull ended for directory '{path}'");
Console.WriteLine();
return 0;
}
di.Refresh();
var checkList = di.GetFiles();
if (checkList.LongLength > 0)
{
Console.CursorVisible = true;
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("Files is not deleted. Some files wich not has been deleted:");
Console.ResetColor();
var cnt = 0;
foreach (var fileInfo in checkList)
{
Console.Error.WriteLine(fileInfo);
cnt++;
if (cnt > 16)
{
Console.Error.WriteLine($"and others: {cnt} files in total");
break;
}
}
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine();
Console.Error.WriteLine("Files is not deleted");
Console.ResetColor();
return 11;
}
try
{
deleteDir(di, progress: progress, verbose: verbose);
progress.showMessage(forced: true);
}
catch (Exception e)
{
Console.Error.WriteLine($"Deletion failed for directory '{di.FullName}' with exception\n{e.Message}\n{e.StackTrace}\n\n");
}
Console.CursorVisible = true;
di.Refresh();
var checkCount = checkList.LongLength;
if (di.Exists)
{
if (progress.doNotDeleteDirectories > 0)
{}
else
{
// Проверяем содержимое всех директорий, включая поддиректории - их не должно быть
// checkCount = di.GetFileSystemInfos().LongLength;
checkCount = 1;
}
if (checkCount > 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Deletion failed for directory '{path}'. Program ended with time {progress.getMessageForEntireTimeOfSanitization}.");
Console.ResetColor();
return 12;
}
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine($"Program ended with time {progress.getMessageForEntireTimeOfSanitization}. Deletion successfull ended for directory '{path}'");
Console.WriteLine();
return 0;
}
// Такая рекурсия нужна, потому что часть файлов могут быть недоступны по каким-то причинам для удаления и мы должны удалить хотя бы то, что можем
static void DeleteFilesFromDir(DirectoryInfo di, List<byte[]> bt, Progress progress, int verbose = 0)
{
// Удаляем файлы в директории
for (int @try = 0; @try < 2; @try++)
{
try
{
var list = di.EnumerateFiles("*", SearchOption.TopDirectoryOnly);
foreach (var file in list)
{
try
{
file.Refresh();
if (file.Exists)
deleteFile(file, bt, progress: progress, true, verbose: verbose);
else
if (verbose >= 2)
Console.WriteLine($"File not exists'{file.FullName}' (removed from another program?)");
}
catch (UnauthorizedAccessException e)
{
Console.Error.WriteLine($"Error (PD) for file '{file.FullName}'\n{e.Message}\n{e.StackTrace}");
}
catch (Exception e)
{
Console.Error.WriteLine($"Error (1) for file '{file.FullName}'\n{e.Message}\n{e.StackTrace}");
}
}
}
catch (Exception e)
{
Console.Error.WriteLine($"Error (1) for directory '{di.FullName}'\n{e.Message}\n{e.StackTrace}");
}
}
// Удаляем файлы в поддиректориях
for (int @try = 0; @try < 2; @try++)
{
try
{
var list = di.EnumerateDirectories("*", SearchOption.TopDirectoryOnly);
foreach (var dir in list)
{
try
{
if (dir.LinkTarget is null)
DeleteFilesFromDir(dir, bt: bt, progress: progress, verbose: verbose);
}
catch (Exception e)
{
Console.Error.WriteLine($"Error (1) for subdirectory '{dir.FullName}'\n{e.Message}\n{e.StackTrace}");
}
}
}
catch (Exception e)
{
Console.Error.WriteLine($"Error (2) for directory '{di.FullName}'\n{e.Message}\n{e.StackTrace}");
}
}
}
private static int GetVerboseFlag(string flags)
{
var verbose = flags.Contains("v") ? 1 : 0;
if (verbose > 0)
{
Console.WriteLine("Verbosive mode");
}
if (flags.Contains("vv"))
{
Console.WriteLine("Verbosive mode twiced");
verbose = 2;
}
return verbose;
}
public static int ExecuteSdels(string flagsOfAll, StreamReader stdR)
{
int rc = 0;
var foa = flagsOfAll.Split( new char[] { ':' }, StringSplitOptions.None );
var flags = foa[0];
int verbose = GetVerboseFlag(flags);
if (verbose > 0)
Console.WriteLine("Wait for std.input file names");
do
{
var line = stdR.ReadLine();
if (line == null)
break;
// var sdelName = typeof(MainClass)!.Assembly!.Location;
var sdelName = System.AppContext.BaseDirectory!;
sdelName = Path.Combine(sdelName, "sdel");
var cmdLine = $"'{foa[1]}' '{line}'";
if (verbose > 0)
Console.WriteLine($"Start {sdelName} {cmdLine}");
var psi = new ProcessStartInfo(sdelName, cmdLine);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
using (var pi = Process.Start(psi))
{
if (pi == null)
{
rc = 1;
continue;
}
pi.WaitForExit();
if (pi.ExitCode != 0)
{
Console.ForegroundColor = ConsoleColor.Red;
rc = pi.ExitCode;
}
Console.Error.WriteLine(pi.StandardError.ReadToEnd());
Console.WriteLine(pi.StandardOutput.ReadToEnd());
Console.ResetColor();
}
}
while (true);
if (rc != 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("Error occured");
Console.ResetColor();
}
return rc;
}
private static bool createFile(string path, Progress progress, int verbose)
{
var bt1 = new byte[BufferSize];
// var A = new byte[] { 0x92, 0x49 };
for (int i = 0; i < bt1.Length; i++)
{
bt1[i] = 0;
}
// if (verbose > 0)
Console.WriteLine($"Try to create directory {path}");
if (Directory.Exists(path) || File.Exists(path))
{
Console.WriteLine($"Directory creation failed for path {path} (directory or file already exists). Program terminated");
return false;
}
var dir = new DirectoryInfo(path);
dir.Create();
var mainFileName = "0123456789012345";
var mainFile = new FileInfo(Path.Combine(dir.FullName, mainFileName));
DateTime now, dt = DateTime.MinValue;
TimeSpan ts;
FileStream? fs = null;
if (progress.createDirectoriesOnly <= 0)
try
{
try
{
fs = new FileStream(mainFile.FullName, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1, FileOptions.WriteThrough);
}
catch
{
fs = new FileStream(mainFile.FullName, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.None);
}
if (progress.slowDownFlag > 0)
dt = DateTime.Now;
long offset = 0;
fs.Seek(0, SeekOrigin.Begin);
int lenToWrite = bt1.Length;
var cntOneBytes = 0;
while (cntOneBytes < 16)
{
var cnt = lenToWrite;
try
{
fs.Write(bt1, 0, (int) cnt);
offset += cnt;
fs.Flush();
var sz = offset/1024/1024;
progress.showMessage($"Creation file, Mb: {sz.ToString("#,#")}", true);
}
catch
{
if (lenToWrite == 1)
{
cntOneBytes++;
if (cntOneBytes == 1)
{
var sz = offset/1024/1024;
if (sz > 0)
progress.showMessage($"Creation file, Mb: {sz.ToString("#,#,#")}", true, forced: true);
else
progress.showMessage($"Creation file, bytes: {offset.ToString("#,#,#")}", true, forced: true);
Console.WriteLine(); // Это чтобы был виден прогресс, чтобы его не перезатереть нижеследующим сообщением
}
progress.showMessage($"for creation: try to expand file with 1 bytes, count of tries: {cntOneBytes}", true);
Thread.Sleep(500); // Вдруг ещё место сейчас освободится? Чуть ждём.
dt = DateTime.Now;
}
lenToWrite >>= 1;
if (lenToWrite < 1)
lenToWrite = 1;
}
if (progress.slowDownFlag > 0)
{
now = DateTime.Now;
ts = now - dt;
if (ts.TotalMilliseconds <= MinTimeToSleepInMs)
continue;
Thread.Sleep((int) ts.TotalMilliseconds);
dt = DateTime.Now;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message + "\n\n" + e.StackTrace);
}
finally
{
try
{
fs?.Close();
}
catch
{ }
}
// label1:
Console.WriteLine();
var sb = new StringBuilder();
int len = 1024;
var rnd = new Random();
var cc = 0;
dt = DateTime.MinValue;
if (progress.slowDownFlag > 0)
dt = DateTime.Now;
int ms;
List<DirectoryInfo> diList = new List<DirectoryInfo>();
diList.Add(dir);
var index = 0;
var lastcc = index;
if (progress.createDirectories > 0)
while (len > 0)
{
dir = diList[index];
if (progress.slowDownFlag > 0)
{
now = DateTime.Now;
ms = (int) (now - dt).TotalMilliseconds;
if (ms >= MinTimeToSleepInMs)
{
Thread.Sleep(ms);
dt = DateTime.Now;
}
}
sb.Clear();
progress.showMessage($"(try to create a big count of directories, count of tries: {cc.ToString("#,#,#")}, {lastcc})", true);
for (int i = 0; i < len; i++)
{
var n = rnd.Next(0, 10);
var c = (char) (n + '0');
sb.Append(c);
}
var sbName = sb.ToString();
do
{
try
{
var newDir = dir.CreateSubdirectory(sbName);
cc++;
lastcc = index;
// Защита от того, что мы запомним слишком много директорий
if (diList.Count < 1_000_000)
diList.Add(newDir);
break;
}
catch
{
if (index <= 1)
len--;
else
len >>= 1;
sbName = sbName.Substring(startIndex: 0, length: len);
if (sbName.Length <= 0 || len <= 0)
{
// Выходим, если не создано ни одной директории в главной директории
if (cc == 0)
{
len = 0;
break;
}
// Будем создавать директории в субдиректориях: на всякий случай. Они обычно не создаются, но бывают исключения
index++;
if (index >= diList.Count)
{
len = 0;
break;
}
if (index - lastcc > 16)
{
len = 0;
break;
}
len = 1024;
break;
}
}
}
while (true);
}
progress.showMessage($"(try to create a big count of directories, count of tries: {cc.ToString("#,#,#")}, {lastcc})", true, forced: true);
Thread.Sleep(500);
Console.WriteLine(); // Перевод строки после progress.showMessage
return true;
}
/// <summary>Инициализирует массив одним и тем же значением на весь массив</summary>
/// <param name="bt">Список для добавления массива</param>
/// <param name="pattern">Шаблон заполнения</param>
private static void ArrayInitialization(List<byte[]> bt, byte pattern)
{
var bt0 = new byte[BufferSize];
for (int i = 0; i < bt0.Length; i++)
{
bt0[i] = pattern;
}
bt.Add(bt0);
}
private static void deleteDir(DirectoryInfo dir, Progress progress, int verbose = 0)
{
if (progress.doNotDeleteDirectories > 0)
return;
var oldDirName = dir.FullName;
if (verbose > 0)
Console.WriteLine($"Try to delete directory \"{dir.FullName}\"");
// Также пропускаем ссылки, не проходя по ним. То есть мы сейчас не будем перечислять директорию, которая является ссылкой
if (dir.LinkTarget is null)
{
var dirList = dir.GetDirectories();
foreach (var di in dirList)
{
try
{
deleteDir(di, progress: progress, verbose: verbose);
}
catch (UnauthorizedAccessException e)
{
Console.Error.WriteLine($"Error for dir {di.FullName}\n{e.Message}\n{e.StackTrace}");
}