-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopyFileEngine_1.cs
More file actions
570 lines (493 loc) · 17.8 KB
/
Copy pathCopyFileEngine_1.cs
File metadata and controls
570 lines (493 loc) · 17.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
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using netCommander.FileSystemEx;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace netCommander
{
/// <summary>
/// self implementaion with dot net streams
/// </summary>
public class CopyFileEngine_1 : CopyFileEngineBase
{
//use read and write to framework streams
public CopyFileEngine_1(string[] source, string destination, CopyEngineOptions options, CopyFileProgressDialog dialog)
: base(source, destination, options, dialog)
{
}
private int buffer_size;
private int buffers_count;
private long total_bytes_transferred = 0L;
private int items_count = 0;
private long total_size = 0L;
private bool enable_total_progress = false;
private byte[] buffer_sync = new byte[0]; //late init
private StreamAsyncWriter buffers_async = null; //late init
public override void DoCopy()
{
throw new NotImplementedException();
}
private object total_transferred_lock = new object();
public long TotalTransferredSafe
{
get
{
long ret = 0L;
lock (total_transferred_lock)
{
ret = total_bytes_transferred;
}
return ret;
}
set
{
lock (total_transferred_lock)
{
total_bytes_transferred = value;
}
}
}
private bool internal_is_same_volume(IntPtr h1, IntPtr h2)
{
BY_HANDLE_FILE_INFORMATION info1 = new BY_HANDLE_FILE_INFORMATION();
BY_HANDLE_FILE_INFORMATION info2 = new BY_HANDLE_FILE_INFORMATION();
int res = Native.GetFileInformationByHandle(h1, ref info1);
if (res == 0)
{
return false;
}
res = Native.GetFileInformationByHandle(h2, ref info2);
if (res == 0)
{
return false;
}
return (info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber);
}
private FileStream internal_create_source_stream(string file_name)
{
FileStream ret = null;
IntPtr file_hanle = IntPtr.Zero;
file_hanle = Native.CreateFile_intptr
(file_name,
Win32FileAccess.GENERIC_READ,
FileShare.Read,
IntPtr.Zero,
FileMode.Open,
CreateFileOptions.SEQUENTIAL_SCAN,
IntPtr.Zero);
if (file_hanle.ToInt32() == Native.INVALID_HANDLE_VALUE)
{
int win_err = Marshal.GetLastWin32Error();
Win32Exception ex = new Win32Exception(win_err);
throw ex;
}
try
{
ret = new FileStream
(file_hanle,
FileAccess.Read,
true,
buffer_size);
return ret;
}
catch (Exception ex2)
{
Native.CloseHandle(file_hanle);
throw ex2;
}
}
private FileStream internal_create_destination_stream(string file_name, long file_size)
{
FileStream ret = null;
IntPtr file_handle = IntPtr.Zero;
file_handle = Native.CreateFile_intptr
(file_name,
Win32FileAccess.GENERIC_WRITE,
FileShare.Read,
IntPtr.Zero,
(options & CopyEngineOptions.NoRewrite) == CopyEngineOptions.NoRewrite ? FileMode.CreateNew : FileMode.Create,
CreateFileOptions.None,
IntPtr.Zero);
if (file_handle.ToInt32() == Native.INVALID_HANDLE_VALUE)
{
int win_err = Marshal.GetLastWin32Error();
Win32Exception ex = new Win32Exception(win_err);
throw ex;
}
try
{
ret = new FileStream
(file_handle,
FileAccess.Write,
true,
buffer_size);
ret.SetLength(file_size);
return ret;
}
catch (Exception ex2)
{
Native.CloseHandle(file_handle);
throw ex2;
}
}
private void copy_proc()
{
//now we have initial_source[] and destination
//see initial_destination
//initial_destination may be directory or file or file stream
//and it may existent or no
if (IOhelper.PathIsFileStream(initial_destination))
{
//copy_dest_file_stream();
}
}
private void copy_recurs(string source_file, string destination_file)
{
}
private void copy_destination_dir()
{
//i.e. existing directory
//
//copy all contens of inital_source INTO existing dir
//
for (int i = 0; i < initial_source.Length; i++)
{
if (AbortJob)
{
break;
}
}
}
private void copy_destination_file()
{
//i.e. existing file
//initial source must be ONE file
//copy default and alternate file streams
if (initial_source.Length > 1)
{
Messages.ShowMessage(string.Format
("Wrong destination.\nCannot copy more then one file to file\n'{0}'.",
initial_destination));
return;
}
WIN32_FIND_DATA src_data = new WIN32_FIND_DATA();
if (!Wrapper.GetFileInfo(initial_source[0], ref src_data))
{
Messages.ShowMessage(string.Format
("Cannot find source\n'{0}'.",
initial_source[0]));
return;
}
if ((src_data.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory)
{
Messages.ShowMessage("Cannot copy directory into existing file.");
return;
}
string source = initial_source[0];
string destination = initial_destination;
string source_actual = string.Empty;
string destination_actual = string.Empty;
WrapperNT.FileStream_enum fs_enum = new WrapperNT.FileStream_enum(initial_source[0]);
foreach (NT_FILE_STREAM_INFORMATION s_info in fs_enum)
{
if (s_info.StreamName == "::$DATA")
{
//for default stream, skip stream name
source_actual = source;
destination_actual = destination;
}
else
{
source_actual = source + s_info.StreamName;
destination_actual = destination + s_info.StreamName;
}
copy_one_item(source_actual, destination_actual);
}
}
private void copy_destination_stream()
{
//initial source must be ONE file
if (initial_source.Length > 1)
{
Messages.ShowMessage(string.Format
("Wrong destination.\nCannot copy more then one file to file stream\n'{0}'.",
initial_destination));
return;
}
WIN32_FIND_DATA src_data = new WIN32_FIND_DATA();
if (!Wrapper.GetFileInfo(initial_source[0], ref src_data))
{
Messages.ShowMessage(string.Format
("Cannot find source\n'{0}'.",
initial_source[0]));
return;
}
if ((src_data.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory)
{
Messages.ShowMessage("Cannot copy directory into file stream.");
return;
}
copy_one_item(initial_source[0], initial_destination);
}
private void copy_one_item(string source, string destination)
{
FileStream src_stream = null;
FileStream dest_stream = null;
//try open source
try
{
src_stream = internal_create_source_stream(source);
}
catch (Exception ex)
{
if (src_stream != null)
{
src_stream.Close();
}
AbortJob = !process_error
(string.Format("Cannot open source file '{0}'", source),
ex);
return;
}
//try open destination
try
{
dest_stream = internal_create_destination_stream(destination, src_stream.Length);
}
catch (Exception ex)
{
src_stream.Close();
if (dest_stream != null)
{
dest_stream.Close();
}
AbortJob = !process_error
(string.Format("Cannot open destination file\n'{0}'.", destination),
ex);
return;
}
CopyStreamItem copy_item = new CopyStreamItem();
copy_item.BytesTransferred = 0;
copy_item.DestinationName = destination;
copy_item.DestinationStream = dest_stream;
copy_item.SourceName = source;
copy_item.SourceStream = src_stream;
//which method use?
if (internal_is_same_volume(src_stream.Handle, dest_stream.Handle))
{
//same volume - sync copy
copy_io_stream_sync(copy_item);
}
else
{
//cross volumes - use async writer
copy_io_stream_async(copy_item);
}
}
private void copy_io_stream_sync(CopyStreamItem item)
{
if (buffer_sync.Length == 0)
{
buffer_sync = new byte[buffer_size];
}
int bytes_readed = 0;
bool continue_copy = true;
while (continue_copy)
{
bytes_readed = item.SourceStream.Read(buffer_sync, 0, buffer_size);
//notifu chunk read
item.DestinationStream.Write(buffer_sync, 0, bytes_readed);
continue_copy = bytes_readed != 0;
item.BytesTransferred += bytes_readed;
//time to notify chunk write
}
}
private void copy_io_stream_async(CopyStreamItem item)
{
if (buffer_sync == null)
{
buffers_async = new StreamAsyncWriter();
buffers_async.WriteChunkCallback = new WriteChunk(write_chunk_finish_async);
buffers_async.PrepareBuffers(buffers_count, buffer_size);
}
int bytes_readed = 0;
bool continue_copy = true;
while (continue_copy)
{
StreamWriterBuffer buf = buffers_async.WaitForFreeBuffer();
bytes_readed = item.SourceStream.Read(buf.buffer, 0, buffer_size);
buf.ActualBytes = bytes_readed;
buf.DestinationStream = item.DestinationStream;
buf.DestinationName = item.DestinationName;
buffers_async.Enqueue(buf);
//notify chunk read finish
continue_copy = bytes_readed != 0;
}
}
private void write_chunk_finish_async(string destination, int chunk_len)
{
//will be call from write thread from buffers_async!
TotalTransferredSafe = TotalTransferredSafe + chunk_len;
//now notify chunk write finish
}
}//end class
public class StreamAsyncWriter : IDisposable
{
private Queue<StreamWriterBuffer> queue_write = new Queue<StreamWriterBuffer>();
private object queue_write_lock = new object();
private Queue<StreamWriterBuffer> queue_free = new Queue<StreamWriterBuffer>();
private object queue_free_lock = new object();
private EventWaitHandle wait_queue_free_ready = new EventWaitHandle(false, EventResetMode.AutoReset);
private EventWaitHandle wait_queque_write_ready = new EventWaitHandle(false, EventResetMode.AutoReset);
public StreamAsyncWriter()
{
Thread write_thread = new Thread(internal_write);
write_thread.Start();
}
public WriteChunk WriteChunkCallback;
public int ActiveBuffersCount
{
get
{
int ret = 0;
lock (queue_write_lock)
{
ret = queue_write.Count;
}
return ret;
}
}
public int FreeBuffersCount
{
get
{
int ret = 0;
lock (queue_free_lock)
{
ret = queue_free.Count;
}
return ret;
}
}
public StreamWriterBuffer WaitForFreeBuffer()
{
wait_queue_free_ready.Reset();
if (FreeBuffersCount == 0)
{
wait_queue_free_ready.WaitOne();
}
StreamWriterBuffer ret = null;
lock (queue_free_lock)
{
ret = queue_free.Dequeue();
}
return ret;
}
public void Enqueue(StreamWriterBuffer chunk)
{
lock (queue_write_lock)
{
queue_write.Enqueue(chunk);
}
//allow write thread proceed
wait_queque_write_ready.Set();
}
public void PrepareBuffers(int buffers_count, int buffer_size)
{
for (int i = 0; i < buffers_count; i++)
{
StreamWriterBuffer new_buf = new StreamWriterBuffer(buffer_size);
lock (queue_free_lock)
{
queue_free.Enqueue(new_buf);
}
}
wait_queue_free_ready.Set();
}
private StreamWriterBuffer WaitForReadyBuffer()
{
wait_queque_write_ready.Reset();
StreamWriterBuffer ret = null;
if (ActiveBuffersCount == 0)
{
wait_queque_write_ready.WaitOne();
}
lock (queue_write_lock)
{
ret = queue_write.Dequeue();
}
return ret;
}
private void ReleaseBuffer(StreamWriterBuffer chunk)
{
lock (queue_free_lock)
{
queue_free.Enqueue(chunk);
}
wait_queue_free_ready.Set();
}
private void internal_write()
{
while (true)
{
StreamWriterBuffer chunk = WaitForReadyBuffer();
if (chunk.DestinationStream == null)
{
break;
}
chunk.DestinationStream.Write(chunk.buffer, 0, chunk.ActualBytes);
ReleaseBuffer(chunk);
if (WriteChunkCallback != null)
{
WriteChunkCallback(chunk.DestinationName, chunk.ActualBytes);
}
}//end while
}
#region IDisposable Members
public void Dispose()
{
//add to write queue buffer with destination_stream=null
//when write thread dequeue such buffer, write thread terminates
StreamWriterBuffer fake_buffer = new StreamWriterBuffer(0);
Enqueue(fake_buffer);
}
#endregion
}
public class CopyStreamItem
{
public string SourceName { get; set; }
public string DestinationName { get; set; }
public Stream SourceStream { get; set; }
public Stream DestinationStream { get; set; }
public long BytesTransferred { get; set; }
}
public class StreamWriterBuffer
{
public byte[] buffer;
public string DestinationName { get; set; }
public Stream DestinationStream { get; set; }
public int ActualBytes { get; set; }
public int BufferSize { get; private set; }
public StreamWriterBuffer(int buffer_size)
{
BufferSize = buffer_size;
buffer = new byte[buffer_size];
ActualBytes = 0;
DestinationStream = null;
DestinationName = string.Empty;
}
}
public class CopyChunkTransferredEventArgs : EventArgs
{
public CopyStreamItem CopyItem { get; private set; }
public CopyChunkTransferredEventArgs(CopyStreamItem item)
{
CopyItem = item;
}
}
public delegate void CopyChunkTransferredEventHandler(object sender, CopyChunkTransferredEventArgs e);
public delegate void WriteChunk(string destinaton_name, int chunk_length);
}