You could try to change the code like this
public bool CopyFileAndFolder(string sourceFolder, string replacePath)
{
bool result = false;
try
{
foreach (string extractPath in Directory.GetDirectories(sourceFolder, "*", SearchOption.AllDirectories))
{
string destFolder = extractPath.Replace(sourceFolder, replacePath);
if (!Directory.Exists(destFolder))
Directory.CreateDirectory(destFolder);
foreach (string extractFile in Directory.GetFiles(sourceFolder, "*.*", SearchOption.AllDirectories))
{
string destFile = Path.Combine(destFolder, Path.GetFileName(extractFile));
File.Copy(extractFile, destFile, true);
}
}
result = true;
}
catch (Exception ex)
{
result = false;
Trace.WriteLine(ex.Message);
}
return result;
}
That is, move the file copy loop into the directory search loop and change the destination path a bit.
[UPDATE]
I found it easier to make this method recursive instead. As far as I can tell it works for me.
public bool CopyFileAndFolder(string sourceFolder, string backupPath)
{
bool retVal = false;
try
{
if (!Directory.Exists(backupPath))
Directory.CreateDirectory(backupPath);
foreach (string fileName in Directory.GetFiles(sourceFolder, "*.*", SearchOption.TopDirectoryOnly))
{
string destFile = Path.Combine(backupPath, Path.GetFileName(fileName));
File.Copy(fileName, destFile, true);
}
string[] directories = Directory.GetDirectories(sourceFolder, "*", SearchOption.TopDirectoryOnly);
if (directories.Length == 0)
return true;
foreach (string directory in directories)
{
string destFolder = Path.Combine(backupPath, Path.GetFileName(directory));
retVal = CopyFileAndFolder(directory, destFolder);
if (!retVal)
break;
}
}
catch (Exception ex)
{
retVal = false;
Trace.WriteLine(ex.Message);
}
return retVal;
}