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: .net 1.1, .net 2.0, .net 3.0, ADO.NET, c#, c-sharp, controls, copy, DataSet, datasource, directory, Framework, internet-life, query, tech-review, Visual Studio 2008, visual-studio-2005, winforms.
Trackback this post | Subscribe to the comments via RSS Feed