how to copy a directory in c-sharp

July 2, 2008

this is a function  to copy all files in a directory.

public static void Copy(DirectoryInfo diSource, DirectoryInfo diDestination, string FileFilter, string DirectoryFilter, bool Overwrite, int FolderLimit)
{
int iterator = 0;
List<DirectoryInfo> diSourceList = new List<DirectoryInfo>();
List<FileInfo> fiSourceList = new List<FileInfo>();

try
{
///// Error Checking /////
if (diSource == null)
throw new ArgumentException(”Source Directory: NULL”);
if (diDestination == null)
throw new ArgumentException(”Destination Directory: NULL”);
if (!diSource.Exists)
throw new IOException(”Source Directory: Does Not Exist”);
if (!(FolderLimit > 0))
throw new ArgumentException(”Folder Limit: Less Than 1″);
if (DirectoryFilter == null || DirectoryFilter == string.Empty)
DirectoryFilter = “*”;
if (FileFilter == null || FileFilter == string.Empty)
FileFilter = “*”;

///// Add Source Directory to List /////
diSourceList.Add(diSource);

///// First Section: Get Folder/File Listing /////
while (iterator < diSourceList.Count && iterator < FolderLimit)
{
foreach (DirectoryInfo di in diSourceList[iterator].GetDirectories(DirectoryFilter))
diSourceList.Add(di);

foreach (FileInfo fi in diSourceList[iterator].GetFiles(FileFilter))
fiSourceList.Add(fi);

iterator++;
}

///// Second Section: Create Folders from Listing /////
foreach (DirectoryInfo di in diSourceList)
{
if (di.Exists)
{
string sFolderPath = diDestination.FullName + @”\” + di.FullName.Remove(0, diSource.FullName.Length);

///// Prevent Silly IOException /////
if (!Directory.Exists(sFolderPath))
Directory.CreateDirectory(sFolderPath);
}
}

///// Third Section: Copy Files from Listing /////
foreach (FileInfo fi in fiSourceList)
{
if (fi.Exists)
{
string sFilePath = diDestination.FullName + @”\” + fi.FullName.Remove(0, diSource.FullName.Length);

///// Better Overwrite Test W/O IOException from CopyTo() /////
if (Overwrite)
fi.CopyTo(sFilePath, true);
else
{
///// Prevent Silly IOException /////
if (!File.Exists(sFilePath))
fi.CopyTo(sFilePath, true);
}
}
}
}
catch
{ throw; }
}

Entry Filed under: c-sharp. Tags: , , , , , , , , , , , , , , , , , .


Archives

Other

Categories

 

July 2008
M T W T F S S
« Jun   Aug »
 123456
78910111213
14151617181920
21222324252627
28293031  

Tags