10
mai
2007
Directory.Copy
mai
2007
A ma grande surprise, la méthode Copy n’existe pas sur la classe Directory. Bien que je pense que cela a déjà été fait 1000 fois et qu’on peut sûrement trouver plein de sources sur le web, je l’ai refaite :
public static class DirectoryExtension
{
public static bool Copy(string sourcePath, string destPath)
{
if (!Directory.Exists(sourcePath))
throw new IOException();
if (Directory.Exists(destPath))
{
try
{
Directory.Delete(destPath, true);
}
catch
{
return false;
}
}
if (File.Exists(destPath))
{
try
{
File.Delete(destPath);
}
catch
{
return false;
}
}
OnlyCopy(sourcePath, destPath);
return true;
}
private static void OnlyCopy(string sourcePath, string destPath)
{
Directory.CreateDirectory(destPath);
foreach (string subDirectoryPath in Directory.GetDirectories(sourcePath))
OnlyCopy(subDirectoryPath, destPath + @"\" + DirectoryName(subDirectoryPath));
foreach (string filePath in Directory.GetFiles(sourcePath))
File.Copy(filePath, destPath + @"\" + FileName(filePath));
}
private static string FileName(string filePath)
{
return Name(filePath);
}
private static string DirectoryName(string directoryPath)
{
return Name(directoryPath);
}
private static string Name(string path)
{
return path.Remove(0, path.LastIndexOf('\') + 1);
}
}
{
public static bool Copy(string sourcePath, string destPath)
{
if (!Directory.Exists(sourcePath))
throw new IOException();
if (Directory.Exists(destPath))
{
try
{
Directory.Delete(destPath, true);
}
catch
{
return false;
}
}
if (File.Exists(destPath))
{
try
{
File.Delete(destPath);
}
catch
{
return false;
}
}
OnlyCopy(sourcePath, destPath);
return true;
}
private static void OnlyCopy(string sourcePath, string destPath)
{
Directory.CreateDirectory(destPath);
foreach (string subDirectoryPath in Directory.GetDirectories(sourcePath))
OnlyCopy(subDirectoryPath, destPath + @"\" + DirectoryName(subDirectoryPath));
foreach (string filePath in Directory.GetFiles(sourcePath))
File.Copy(filePath, destPath + @"\" + FileName(filePath));
}
private static string FileName(string filePath)
{
return Name(filePath);
}
private static string DirectoryName(string directoryPath)
{
return Name(directoryPath);
}
private static string Name(string path)
{
return path.Remove(0, path.LastIndexOf('\') + 1);
}
}