Skip to content

Instantly share code, notes, and snippets.

@AmirMahdyJebreily
Created December 24, 2023 11:28
Show Gist options
  • Save AmirMahdyJebreily/8b53aca62804204eef94f6c9f9145d67 to your computer and use it in GitHub Desktop.
Save AmirMahdyJebreily/8b53aca62804204eef94f6c9f9145d67 to your computer and use it in GitHub Desktop.
Deep copy, for copying a folder and all its contents
double _progressCopy;
double _progressAll;
string primeFolderPath = Console.ReadLine(),
destFolderPath = Console.ReadLine();
try
{
var sourceDir = new DirectoryInfo(primeFolderPath);
await DeepCopy(sourceDir, destFolderPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
async Task DeepCopy(DirectoryInfo directory, string destinationDir)
{
_progressAll = 0;
foreach (string dir in Directory.GetDirectories(directory.FullName, "*", SearchOption.AllDirectories))
{
string dirToCreate = dir.Replace(directory.FullName, destinationDir);
Directory.CreateDirectory(dirToCreate);
}
var filesForCopy = Directory.GetFiles(directory.FullName, "*.*", SearchOption.AllDirectories);
int index = 0;
foreach (string newPath in filesForCopy)
{
index++;
var FileAPI = new CustomFileCopier(newPath, newPath.Replace(directory.FullName, destinationDir));
FileAPI.Copy();
FileAPI.OnProgressChanged += ProgressFile;
_progressAll = (double)(index / filesForCopy.Length) * 100d;
await Task.Delay(1);
}
void ProgressFile(double Percentage, ref bool Cancel)
{
_progressCopy = Percentage;
}
}
public delegate void ProgressChangeDelegate(double Percentage, ref bool Cancel);
public delegate void Completedelegate();
class CustomFileCopier
{
public CustomFileCopier(string Source, string Dest)
{
this.SourceFilePath = Source;
this.DestFilePath = Dest;
OnProgressChanged += delegate { };
OnComplete += delegate { };
}
public void Copy()
{
byte[] buffer = new byte[1024 * 1024]; // 1MB buffer
bool cancelFlag = false;
using (FileStream source = new FileStream(SourceFilePath, FileMode.Open, FileAccess.Read))
{
long fileLength = source.Length;
using (FileStream dest = new FileStream(DestFilePath, FileMode.CreateNew, FileAccess.Write))
{
long totalBytes = 0;
int currentBlockSize = 0;
while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytes += currentBlockSize;
double percentage = (double)totalBytes * 100.0 / fileLength;
dest.Write(buffer, 0, currentBlockSize);
cancelFlag = false;
OnProgressChanged(percentage, ref cancelFlag);
if (cancelFlag == true)
{
// Delete dest file here
break;
}
}
}
}
OnComplete();
}
public string SourceFilePath { get; set; }
public string DestFilePath { get; set; }
public event ProgressChangeDelegate OnProgressChanged;
public event Completedelegate OnComplete;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment