/// <summary> /// Raises UnitCopy Event /// </summary> /// <param name="e"></param> protected virtual void OnUnitCopy(UnitCopyEventArgs e) { if (UnitCopy != null) { UnitCopy(this, e); } }
/// <summary> /// Copies a file in units /// </summary> /// <param name="source">Source File</param> /// <param name="target">Target File</param> /// <param name="unit">Number of bytes that is copied at once. Reverted to 2^20 if 0</param> /// <param name="overwriteTarget">Specifies whether the target file is over writen is it already exists otherwise an exception is thrown</param> public void Copy(string source, string target, int unit, bool overwriteTarget) { // Create target folder in case it doesent't exist Directory.CreateFolder(GetFileParent(target)); // set defaults if (unit == 0) { unit = (int)Math.Pow(2, 20); // 1 MB } FileMode targetMode; if (overwriteTarget) { targetMode = FileMode.Create; } else { targetMode = FileMode.CreateNew; } // Streams FileStream sourceStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream targetStream = new FileStream(target, targetMode, FileAccess.Write, FileShare.None); BinaryReader sourceReader = new BinaryReader(sourceStream); BinaryWriter targetWriter = new BinaryWriter(targetStream); // Counters int loopCount = (int)(sourceStream.Length / unit); long bytesleft = sourceStream.Length; if (bytesleft <= unit) { unit = (int)bytesleft; } // Copier Loop for (int i = 0; i <= loopCount; i++) { targetWriter.Write(sourceReader.ReadBytes(unit)); // Perform Copying // Call Event Raiser UnitCopyEventArgs e = new UnitCopyEventArgs(source, target, sourceStream.Length, sourceStream.Length - bytesleft, unit); this.OnUnitCopy(e); bytesleft -= unit; if (bytesleft <= unit) { unit = (int)bytesleft; } // Check for stop if (m_resume == false) { // Close Streams sourceReader.Close(); targetWriter.Close(); sourceStream.Close(); targetStream.Close(); // delete current file System.IO.File.Delete(target); // Call Event Raiser this.OnAfterStop(); // exit loop break; } } // Close Streams sourceReader.Close(); targetWriter.Close(); sourceStream.Close(); targetStream.Close(); }