using
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace DeployUtil
{
public class CopyUtil
{
public static void Sync(string sourcePath, string destinationPath)
{
bool dirExisted = DirExists(destinationPath);
//get the source files
string[] srcFiles = Directory.GetFiles(sourcePath);
foreach (string sourceFile in srcFiles)
{
FileInfo sourceInfo = new FileInfo(sourceFile);
string destFile = Path.Combine(destinationPath, sourceInfo.Name);
if (!dirExisted && File.Exists(destFile))
{
FileInfo destInfo = new FileInfo(destFile);
if (sourceInfo.LastWriteTime > destInfo.LastWriteTime)
{
//file is newer, so copy it
File.Copy(sourceFile, Path.Combine(destinationPath, sourceInfo.Name), true);
Console.WriteLine(sourceFile + " copied (newer version)");
}
}
else
{
File.Copy(sourceFile, Path.Combine(destinationPath, sourceInfo.Name));
Console.WriteLine(sourceFile + " copied");
}
}
DeleteOldDestinationFiles(srcFiles, destinationPath);
//now process the directories if exist
string[] dirs = Directory.GetDirectories(sourcePath);
foreach (string dir in dirs)
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
//recursive do the directories
Sync(dir, Path.Combine(destinationPath, dirInfo.Name));
}
}
private static bool DirExists(string path)
{
//create destination directory if not exist
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
return true;
}
else
{
return false;
}
}
private static void DeleteOldDestinationFiles(string[] sourceFiles, string destinationPath)
{
//get the destination files
string[] dstFiles = Directory.GetFiles(destinationPath);
foreach (string dstFile in dstFiles)
{
FileInfo f = new FileInfo(dstFile);
string[] found = Array.FindAll(sourceFiles, str => GetName(str).Equals(f.Name));
if (found.Length == 0)
{
//delete file if not found in destination
File.Delete(dstFile);
LogInfo(dstFile + " deleted");
}
}
}
private static string GetName(string path)
{
FileInfo i = new FileInfo(path);
return i.Name;
}
private static void LogInfo(string text)
{
ConsoleColor was = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine(text);
Console.ForegroundColor = was;
}
}
}
Geen opmerkingen:
Een reactie posten