Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
710 lines (645 loc) · 32.8 KB
/
Copy pathProgram.cs
File metadata and controls
710 lines (645 loc) · 32.8 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
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Globalization;
using Microsoft.Win32.SafeHandles;
namespace RufusAnalog
{
public static class Localization
{
public static string FormTitle { get; private set; } = "USB-mgr";
public static string UsbDevices { get; private set; } = "USB Devices";
public static string IsoFile { get; private set; } = "ISO File";
public static string Browse { get; private set; } = "Browse";
public static string Exit { get; private set; } = "Exit";
public static string Start { get; private set; } = "Start";
public static string SelectUsbAndIso { get; private set; } = "Please select a USB device and an ISO file.";
public static string EraseWarning { get; private set; } = "This will erase all data on {0}. Continue?";
public static string Warning { get; private set; } = "Warning";
public static string NoPhysicalDrive { get; private set; } = "Cannot find physical drive.";
public static string StartingProcess { get; private set; } = "Starting process...";
public static string FormattingUsb { get; private set; } = "Cleaning USB drive (deleting files only)...";
public static string MountingIso { get; private set; } = "Mounting ISO...";
public static string IsoMountedAt { get; private set; } = "ISO mounted at {0}";
public static string CopyingFiles { get; private set; } = "Copying files to USB...";
public static string DismountingIso { get; private set; } = "Dismounting ISO...";
public static string BootableSuccess { get; private set; } = "Bootable USB created successfully!";
public static string Success { get; private set; } = "Success";
public static string ErrorFormat { get; private set; } = "Error: {0}";
public static string Error { get; private set; } = "Error";
public static string WaitingUsb { get; private set; } = "Waiting for USB drive to be detected...";
public static string UsbDetectedAt { get; private set; } = "USB drive detected at {0}";
public static string NoIsoLetter { get; private set; } = "Cannot detect mounted ISO drive letter: {0}";
public static string NoUsbLetterAfterFormat { get; private set; } = "Cannot find USB drive letter.";
public static string MountOutput { get; private set; } = "Mount output: {0}";
public static string CreateFileFailed { get; private set; } = "CreateFile failed: {0}";
public static string DeviceIoControlFailed { get; private set; } = "DeviceIoControl failed: {0}";
public static string CleanupFiles { get; private set; } = "Deleting existing files and folders (excluding system folders)...";
public static string CleanupComplete { get; private set; } = "Cleanup complete.";
static Localization()
{
string lang = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName.ToLower();
if (lang == "ru")
{
FormTitle = "USB-mgr";
UsbDevices = "USB-устройства";
IsoFile = "Файл ISO";
Browse = "Обзор";
Exit = "Выход";
Start = "Старт";
SelectUsbAndIso = "Пожалуйста, выберите USB-устройство и файл ISO.";
EraseWarning = "Это удалит все данные на {0}. Продолжить?";
Warning = "Предупреждение";
NoPhysicalDrive = "Не удается найти физический диск.";
StartingProcess = "Запуск процесса...";
FormattingUsb = "Очистка USB-накопителя (удаление файлов без форматирования)...";
MountingIso = "Монтирование ISO...";
IsoMountedAt = "ISO смонтирован на {0}";
CopyingFiles = "Копирование файлов на USB...";
DismountingIso = "Размонтирование ISO...";
BootableSuccess = "Загрузочный USB создан успешно!";
Success = "Успех";
ErrorFormat = "Ошибка: {0}";
Error = "Ошибка";
WaitingUsb = "Ожидание обнаружения USB-накопителя...";
UsbDetectedAt = "USB-накопитель обнаружен на {0}";
NoIsoLetter = "Не удается обнаружить букву смонтированного ISO-диска: {0}";
NoUsbLetterAfterFormat = "Не удается найти букву USB-диска.";
MountOutput = "Вывод монтирования: {0}";
CreateFileFailed = "CreateFile не удался: {0}";
DeviceIoControlFailed = "DeviceIoControl не удался: {0}";
CleanupFiles = "Удаление существующих файлов и папок (кроме системных)...";
CleanupComplete = "Очистка завершена.";
}
else if (lang == "ka")
{
FormTitle = "USB-mgr";
UsbDevices = "USB მოწყობილობები";
IsoFile = "ISO ფაილი";
Browse = "დათვალიერება";
Exit = "გასვლა";
Start = "დაწყება";
SelectUsbAndIso = "გთხოვთ, აირჩიოთ USB მოწყობილობა და ISO ფაილი.";
EraseWarning = "ეს წაშლის ყველა მონაცემს {0}-ზე. გაგრძელება?";
Warning = "გაფრთხილება";
NoPhysicalDrive = "ფიზიკური დისკის პოვნა შეუძლებელია.";
StartingProcess = "პროცესის დაწყება...";
FormattingUsb = "USB დისკის გასუფთავება (მხოლოდ ფაილების წაშლა, ფორმატირების გარეშე)...";
MountingIso = "ISO-ს მონტაჟი...";
IsoMountedAt = "ISO მონტაჟირებულია {0}-ზე";
CopyingFiles = "ფაილების კოპირება USB-ზე...";
DismountingIso = "ISO-ს დემონტაჟი...";
BootableSuccess = "ჩატვირთვადი USB წარმატებით შეიქმნა!";
Success = "წარმატება";
ErrorFormat = "შეცდომა: {0}";
Error = "შეცდომა";
WaitingUsb = "USB დრაივის აღმოჩენის ლოდინი...";
UsbDetectedAt = "USB დრაივი აღმოჩენილია {0}-ზე";
NoIsoLetter = "შეუძლებელია მონტაჟირებული ISO დისკის ასოს აღმოჩენა: {0}";
NoUsbLetterAfterFormat = "USB დრაივის ასოს პოვნა შეუძლებელია.";
MountOutput = "მონტაჟის გამოტანა: {0}";
CreateFileFailed = "CreateFile წარუმატებელი: {0}";
DeviceIoControlFailed = "DeviceIoControl წარუმატებელი: {0}";
CleanupFiles = "არსებული ფაილებისა და საქაღალდეების წაშლა (სისტემურების გარდა)...";
CleanupComplete = "გასუფთავება დასრულდა.";
}
else if (lang == "ab")
{
FormTitle = "USB-mgr";
UsbDevices = "USB аҟәарақәа";
IsoFile = "ISO афайл";
Browse = "Аԥхьаара";
Exit = "Аҭыҵра";
Start = "Аԥхьаара";
SelectUsbAndIso = "Ҳаҳәаԥштәи USB аҟәара ала аԥхьаара ала аISO афайл.";
EraseWarning = "Ари аҭыҵра ала адыррақәа {0} ала. Аԥхьаара?";
Warning = "Агәраҳәара";
NoPhysicalDrive = "Афизикатә диск аԥхьаара аҭыҵра ала.";
StartingProcess = "Апроцесс аԥхьаара...";
FormattingUsb = "USB адиск агасупҭауеа (афайлқәа аҭыҵра, аформат ахалхҳәтәуп ала)...";
MountingIso = "ISO амонтирование...";
IsoMountedAt = "ISO амонтировано ала {0}";
CopyingFiles = "Афайлқәа USB ала аԥхьარа...";
DismountingIso = "ISO адисмонтирование...";
BootableSuccess = "Аԥхьаара USB ала аԥхьаара аҭыҵра ала!";
Success = "Аԥхьаара";
ErrorFormat = "Агәра: {0}";
Error = "Агәра";
WaitingUsb = "USB адиск аԥхьაара ала аԥхьაара...";
UsbDetectedAt = "USB адиск ала {0}";
NoIsoLetter = "Амонтировано ISO адиск аԥхьაара ала: {0}";
NoUsbLetterAfterFormat = "USB адиск аԥхьაара ала.";
MountOutput = "Амонт аҭыҵра: {0}";
CreateFileFailed = "CreateFile ала: {0}";
DeviceIoControlFailed = "DeviceIoControl ала: {0}";
CleanupFiles = "Адыррақәа афайлқәа ала асақәа аҭыҵра (асистематә қәа ахалхҳәтәуп ала)...";
CleanupComplete = "Агасупҭауеа аҭыҵра ала.";
}
else if (lang == "ace")
{
FormTitle = "USB-mgr";
UsbDevices = "Alat USB";
IsoFile = "Berkas ISO";
Browse = "Pilih";
Exit = "Keluar";
Start = "Mulai";
SelectUsbAndIso = "Silakan pilih perangkat USB dan berkas ISO.";
EraseWarning = "Ini akan menghapus semua data pada {0}. Lanjutkan?";
Warning = "Peringatan";
NoPhysicalDrive = "Tidak dapat menemukan drive fisik.";
StartingProcess = "Memulai proses...";
FormattingUsb = "Membersihkan drive USB (hanya menghapus file, tanpa format)...";
MountingIso = "Memasang ISO...";
IsoMountedAt = "ISO dipasang di {0}";
CopyingFiles = "Menyalin file ke USB...";
DismountingIso = "Melepas ISO...";
BootableSuccess = "USB bootable berhasil dibuat!";
Success = "Sukses";
ErrorFormat = "Kesalahan: {0}";
Error = "Kesalahan";
WaitingUsb = "Menunggu deteksi drive USB...";
UsbDetectedAt = "Drive USB terdeteksi di {0}";
NoIsoLetter = "Tidak dapat mendeteksi huruf drive ISO yang dipasang: {0}";
NoUsbLetterAfterFormat = "Tidak dapat menemukan huruf drive USB.";
MountOutput = "Output pemasangan: {0}";
CreateFileFailed = "CreateFile gagal: {0}";
DeviceIoControlFailed = "DeviceIoControl gagal: {0}";
CleanupFiles = "Menghapus file dan folder yang ada (kecuali folder sistem)...";
CleanupComplete = "Pembersihan selesai.";
}
// Default: English (already defined above)
}
}
public partial class MainForm : Form
{
private ComboBox usbComboBox;
private TextBox isoTextBox;
private Button browseButton;
private Button exitButton;
private Button startButton;
private TextBox logTextBox;
private ProgressBar progressBar;
private Label usbLabel;
private Label isoLabel;
private bool isWorking = false;
[StructLayout(LayoutKind.Sequential)]
private struct STORAGE_DEVICE_NUMBER
{
public int DeviceType;
public int DeviceNumber;
public int PartitionNumber;
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern SafeFileHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr SecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DeviceIoControl(
SafeFileHandle hDevice,
uint dwIoControlCode,
IntPtr lpInBuffer,
uint nInBufferSize,
out STORAGE_DEVICE_NUMBER lpOutBuffer,
int nOutBufferSize,
out uint lpBytesReturned,
IntPtr lpOverlapped
);
private const uint IOCTL_STORAGE_GET_DEVICE_NUMBER = 0x2D1080;
private const uint GENERIC_READ = 0x80000000;
private const uint FILE_SHARE_READ = 0x00000001;
private const uint FILE_SHARE_WRITE = 0x00000002;
private const uint OPEN_EXISTING = 3;
public MainForm()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.usbComboBox = new ComboBox();
this.isoTextBox = new TextBox();
this.browseButton = new Button();
this.exitButton = new Button();
this.startButton = new Button();
this.logTextBox = new TextBox();
this.progressBar = new ProgressBar();
this.usbLabel = new Label();
this.isoLabel = new Label();
// Form settings
this.Text = Localization.FormTitle;
this.Size = new Size(400, 300);
this.StartPosition = FormStartPosition.CenterScreen;
this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
// USB Devices Label
usbLabel.Text = Localization.UsbDevices;
usbLabel.Location = new Point(10, 10);
this.Controls.Add(usbLabel);
// USB ComboBox
usbComboBox.Location = new Point(10, 30);
usbComboBox.Size = new Size(360, 20);
usbComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
this.Controls.Add(usbComboBox);
// ISO File Label
isoLabel.Text = Localization.IsoFile;
isoLabel.Location = new Point(10, 60);
this.Controls.Add(isoLabel);
// ISO TextBox
isoTextBox.Location = new Point(10, 80);
isoTextBox.Size = new Size(300, 20);
this.Controls.Add(isoTextBox);
// Browse Button
browseButton.Text = Localization.Browse;
browseButton.Location = new Point(320, 80);
browseButton.Size = new Size(50, 20);
browseButton.Click += browseButton_Click;
this.Controls.Add(browseButton);
// Log TextBox
logTextBox.Location = new Point(10, 110);
logTextBox.Size = new Size(360, 80);
logTextBox.Multiline = true;
logTextBox.ReadOnly = true;
logTextBox.ScrollBars = ScrollBars.Vertical;
this.Controls.Add(logTextBox);
// Exit Button
exitButton.Text = Localization.Exit;
exitButton.Location = new Point(10, 200);
exitButton.Click += exitButton_Click;
this.Controls.Add(exitButton);
// Start Button
startButton.Text = Localization.Start;
startButton.Location = new Point(300, 200);
startButton.Click += startButton_Click;
this.Controls.Add(startButton);
// ProgressBar
progressBar.Location = new Point(0, this.ClientSize.Height - 20);
progressBar.Size = new Size(this.ClientSize.Width, 20);
progressBar.Style = ProgressBarStyle.Continuous;
progressBar.ForeColor = Color.Green;
progressBar.BackColor = Color.LightGray;
progressBar.Value = 0;
progressBar.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
this.Controls.Add(progressBar);
this.Load += MainForm_Load;
this.Resize += (s, e) => { progressBar.Width = this.ClientSize.Width; };
}
private void MainForm_Load(object sender, EventArgs e)
{
RefreshUsbList();
}
private void RefreshUsbList()
{
usbComboBox.Items.Clear();
foreach (var drive in DriveInfo.GetDrives())
{
if (drive.DriveType == DriveType.Removable && drive.IsReady)
{
string item = $"{drive.Name} - {drive.VolumeLabel} ({Math.Round(drive.TotalSize / (1024.0 * 1024 * 1024), 1)} GB)";
usbComboBox.Items.Add(item);
}
}
}
private void browseButton_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "ISO files|*.iso";
if (ofd.ShowDialog() == DialogResult.OK)
{
isoTextBox.Text = ofd.FileName;
}
}
private void exitButton_Click(object sender, EventArgs e)
{
Application.Exit();
}
private async void startButton_Click(object sender, EventArgs e)
{
if (isWorking) return;
if (usbComboBox.SelectedIndex == -1 || string.IsNullOrEmpty(isoTextBox.Text))
{
MessageBox.Show(Localization.SelectUsbAndIso);
return;
}
string selectedItem = usbComboBox.SelectedItem.ToString();
string driveLetter = selectedItem.Substring(0, 2); // e.g., "D:"
string isoPath = isoTextBox.Text;
if (MessageBox.Show(string.Format(Localization.EraseWarning, driveLetter), Localization.Warning, MessageBoxButtons.YesNo) == DialogResult.No)
{
return;
}
string physicalDrive = GetPhysicalDriveFromLetter(driveLetter);
if (physicalDrive == null)
{
MessageBox.Show(Localization.NoPhysicalDrive);
return;
}
isWorking = true;
startButton.Enabled = false;
browseButton.Enabled = false;
usbComboBox.Enabled = false;
logTextBox.Clear();
progressBar.Value = 0;
await Task.Run(async () => await CreateBootableUsb(physicalDrive, isoPath));
isWorking = false;
startButton.Enabled = true;
browseButton.Enabled = true;
usbComboBox.Enabled = true;
RefreshUsbList();
}
private async Task CreateBootableUsb(string physicalDrive, string isoPath)
{
try
{
AppendLog(Localization.StartingProcess);
// Step 1: Get USB drive letter & clean files (NO formatting, NO FAT32 check!)
string usbLetter = GetDriveLetterFromPhysical(physicalDrive);
if (string.IsNullOrEmpty(usbLetter))
{
throw new Exception(Localization.NoUsbLetterAfterFormat);
}
AppendLog($"USB drive letter: {usbLetter}");
UpdateProgress(10);
// Delete all non-system files & folders
AppendLog(Localization.CleanupFiles);
try
{
var root = new DirectoryInfo(usbLetter);
foreach (var file in root.GetFiles("*", SearchOption.TopDirectoryOnly))
{
if ((file.Attributes & (FileAttributes.Hidden | FileAttributes.System)) == 0)
{
file.Delete();
}
}
foreach (var dir in root.GetDirectories("*", SearchOption.TopDirectoryOnly))
{
if ((dir.Attributes & (FileAttributes.Hidden | FileAttributes.System)) == 0)
{
dir.Delete(true);
}
}
}
catch (Exception ex)
{
AppendLog($"⚠️ Warning during cleanup: {ex.Message}");
}
AppendLog(Localization.CleanupComplete);
UpdateProgress(30);
// Step 2: Mount ISO
AppendLog(Localization.MountingIso);
string mountCommand = $"-Command \"$di = Mount-DiskImage -ImagePath '{isoPath.Replace("\\", "\\\\")}' -PassThru; (Get-Volume -DiskImage $di).DriveLetter\"";
string mountOutput = await RunProcessAsync("powershell.exe", mountCommand, false);
AppendLog(string.Format(Localization.MountOutput, mountOutput));
string mountedLetterStr = mountOutput.Trim();
if (!string.IsNullOrEmpty(mountedLetterStr) &&
mountedLetterStr.IndexOf("Error", StringComparison.OrdinalIgnoreCase) == -1)
{
string mountedLetter = mountedLetterStr + ":\\";
AppendLog(string.Format(Localization.IsoMountedAt, mountedLetter));
UpdateProgress(40);
// Step 3: Copy files (ultra-fast multithreaded)
AppendLog(Localization.CopyingFiles);
CopyDirectoryWithProgress(mountedLetter, usbLetter + "\\");
UpdateProgress(80);
// Step 4: Dismount ISO
AppendLog(Localization.DismountingIso);
string dismountOutput = await RunProcessAsync("powershell.exe", $"-Command Dismount-DiskImage -ImagePath '{isoPath.Replace("\\", "\\\\")}'", false);
AppendLog(dismountOutput);
UpdateProgress(100);
AppendLog(Localization.BootableSuccess);
InvokeMessageBox(Localization.Success, Localization.BootableSuccess);
}
else
{
throw new Exception(string.Format(Localization.NoIsoLetter, mountOutput));
}
}
catch (OperationCanceledException)
{
AppendLog("Operation canceled by user.");
UpdateProgress(0);
}
catch (Exception ex)
{
AppendLog(string.Format(Localization.ErrorFormat, ex.Message));
UpdateProgress(0);
InvokeMessageBox(Localization.Error, string.Format(Localization.ErrorFormat, ex.Message));
}
}
// 🚀 ULTRA-FAST COPY — 128KB buffer, async, 8 parallel, no WriteThrough
private void CopyDirectoryWithProgress(string sourceDir, string targetDir)
{
AppendLog($"📁 Starting copy from: {sourceDir}");
AppendLog($"📂 Target: {targetDir}");
var files = Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories);
int totalFiles = files.Length;
long totalBytes = files.Sum(f => new FileInfo(f).Length);
long copiedBytes = 0;
var stopwatch = Stopwatch.StartNew();
// 1️⃣ წინასწარ შევქმნათ ყველა საქაღალდე
var directories = new HashSet<string>();
foreach (string file in files)
{
string relativePath = GetRelativePath(sourceDir, file);
string destFile = Path.Combine(targetDir, relativePath);
string destDir = Path.GetDirectoryName(destFile);
if (!string.IsNullOrEmpty(destDir))
{
directories.Add(destDir);
}
}
foreach (string dir in directories)
{
Directory.CreateDirectory(dir);
}
AppendLog($"✅ Created {directories.Count} directories.");
// 2️⃣ მრავალნაკადიანი კოპირება — 8 ერთდროულად
int maxConcurrency = 8;
var semaphore = new SemaphoreSlim(maxConcurrency, maxConcurrency);
var tasks = new List<Task>();
object lockObj = new object();
foreach (string file in files)
{
string f = file; // capture for closure
tasks.Add(Task.Run(async () =>
{
await semaphore.WaitAsync().ConfigureAwait(false);
try
{
string relativePath = GetRelativePath(sourceDir, f);
string destFile = Path.Combine(targetDir, relativePath);
long fileSize = new FileInfo(f).Length;
var fileStopwatch = Stopwatch.StartNew();
// 🔥 128KB buffer, async, გარეშე WriteThrough
using (var sourceStream = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.Read, 131072, FileOptions.Asynchronous | FileOptions.SequentialScan))
using (var destStream = new FileStream(destFile, FileMode.Create, FileAccess.Write, FileShare.None, 131072, FileOptions.Asynchronous))
{
await sourceStream.CopyToAsync(destStream, 131072).ConfigureAwait(false);
}
fileStopwatch.Stop();
lock (lockObj)
{
copiedBytes += fileSize;
int progress = 40 + (int)(40 * (copiedBytes / (double)totalBytes));
UpdateProgress(progress);
}
string sizeStr = FormatBytes(fileSize);
string timeStr = fileStopwatch.Elapsed.TotalSeconds < 1
? $"{fileStopwatch.Elapsed.TotalMilliseconds:0}ms"
: $"{fileStopwatch.Elapsed.TotalSeconds:0.00}s";
AppendLog($"✓ {relativePath} ({sizeStr}) in {timeStr}");
}
catch (Exception ex)
{
AppendLog($"⚠️ {GetRelativePath(sourceDir, f)} → {ex.Message}");
}
finally
{
semaphore.Release();
}
}));
}
// 3️⃣ მოველოდეთ ყველას
Task.WaitAll(tasks.ToArray());
stopwatch.Stop();
// 4️⃣ საბოლოო ანგარიში
string totalSizeStr = FormatBytes(totalBytes);
string elapsed = stopwatch.Elapsed.ToString(@"m\:ss");
double speedMBps = totalBytes / 1024.0 / 1024.0 / stopwatch.Elapsed.TotalSeconds;
AppendLog($"✅ Total: {totalFiles:N0} files ({totalSizeStr}) in {elapsed} | {speedMBps:0.0} MB/s");
}
// დამხმარე მეთოდები
private string GetRelativePath(string basePath, string fullPath)
{
basePath = basePath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
if (fullPath.StartsWith(basePath, StringComparison.OrdinalIgnoreCase))
{
return fullPath.Substring(basePath.Length);
}
return Path.GetFileName(fullPath);
}
private string FormatBytes(long bytes)
{
string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
if (bytes == 0) return "0 B";
int i = (int)Math.Floor(Math.Log(bytes, 1024));
double val = bytes / Math.Pow(1024, i);
return $"{val:0.##} {suffixes[i]}";
}
private async Task<string> RunProcessAsync(string fileName, string arguments, bool runAsAdmin)
{
Process process = new Process();
process.StartInfo.FileName = fileName;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = runAsAdmin;
process.StartInfo.RedirectStandardOutput = !runAsAdmin;
process.StartInfo.RedirectStandardError = !runAsAdmin;
process.StartInfo.CreateNoWindow = true;
if (runAsAdmin) process.StartInfo.Verb = "runas";
process.Start();
string output = "";
if (!runAsAdmin)
{
string stdOut = await process.StandardOutput.ReadToEndAsync();
string stdErr = await process.StandardError.ReadToEndAsync();
output = stdOut.Trim() + (string.IsNullOrEmpty(stdErr) ? "" : "\nError: " + stdErr.Trim());
}
await Task.Run(() => process.WaitForExit());
return output;
}
private void AppendLog(string message)
{
this.Invoke(new Action(() =>
{
logTextBox.AppendText(DateTime.Now.ToString("HH:mm:ss") + " | " + message + "\r\n");
logTextBox.ScrollToCaret();
}));
}
private void UpdateProgress(int value)
{
this.Invoke(new Action(() => progressBar.Value = Math.Min(value, 100)));
}
private void InvokeMessageBox(string title, string message)
{
this.Invoke(new Action(() => MessageBox.Show(message, title)));
}
private int GetDiskNumberFromLetter(string letter)
{
string volPath = @"\\.\" + letter.TrimEnd(':') + ":";
using (SafeFileHandle handle = CreateFile(volPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero))
{
if (handle.IsInvalid)
{
AppendLog(string.Format(Localization.CreateFileFailed, Marshal.GetLastWin32Error()));
return -1;
}
STORAGE_DEVICE_NUMBER sdn;
uint bytesReturned;
if (DeviceIoControl(handle, IOCTL_STORAGE_GET_DEVICE_NUMBER, IntPtr.Zero, 0, out sdn, Marshal.SizeOf(typeof(STORAGE_DEVICE_NUMBER)), out bytesReturned, IntPtr.Zero))
{
return sdn.DeviceNumber;
}
else
{
AppendLog(string.Format(Localization.DeviceIoControlFailed, Marshal.GetLastWin32Error()));
return -1;
}
}
}
private string GetPhysicalDriveFromLetter(string letter)
{
int diskNum = GetDiskNumberFromLetter(letter);
if (diskNum == -1)
{
return null;
}
return @"\\.\PhysicalDrive" + diskNum;
}
private string GetDriveLetterFromPhysical(string physical)
{
string diskNumStr = physical.Replace(@"\\.\PhysicalDrive", "");
if (!int.TryParse(diskNumStr, out int targetDiskNum))
{
return null;
}
foreach (var drive in DriveInfo.GetDrives())
{
if (drive.DriveType == DriveType.Removable && drive.IsReady)
{
string dl = drive.Name.Substring(0, 2);
int dn = GetDiskNumberFromLetter(dl);
if (dn == targetDiskNum)
{
return dl;
}
}
}
return null;
}
}
static class Program
{
[STAThread]
static void Main()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CurrentCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentUICulture;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}