用C#实现目录拷贝

在C#中没有直接的目录拷贝函数,所以需要遍历源目录,然后逐个目录和逐个文件进行拷贝。以下就是实现代码:

/// <summary>

/// Copy files from souce directory to dest directory

/// </summary>

/// <param name="SourceDir"></param>

/// <param name="DestDir"></param>

/// <returns></returns>

private bool CopyFilesExt( string SourceDir, string DestDir )

{

string[] FileNames = Directory.GetFiles(SourceDir);

// Copy files into dest dir

// If file exists, then overwrite

for(int i = 0; i < FileNames.Length; i++ )

File.Copy( FileNames[i],

DestDir + FileNames[i].Substring( SourceDir.Length ), true );

return true;

}

/// <summary>

/// Copy sub-directories and files from directory to dest directory

/// </summary>

/// <param name="SourceDir"></param>

/// <param name="DestDir"></param>

/// <returns></returns>

private bool CopyDirExt( string SourceDir, string DestDir )

{

DirectoryInfo diSource = new DirectoryInfo( SourceDir );

DirectoryInfo diDest = new DirectoryInfo( DestDir );

if( diSource.Exists )

{

// If dest directory doesn't exist, then create it;

if( !diDest.Exists )

diDest.Create();

// Copy files from source directory to dest directory

if( CopyFilesExt( SourceDir, DestDir ) )

{

string[] SubDirs = Directory.GetDirectories( SourceDir );

bool bResult = true;

// Copy sub-directories

for( int i = 0; i < SubDirs.Length; i++ )

if( !CopyDir( SubDirs[i] + @"\",

DestDir + SubDirs[i].Substring( SourceDir.Length ) + @"\" ) )

bResult = false;

return bResult;

}

}

return false;

}

调用如下即可:

strSourceDir = txtSourceDir.Text;

strDestDir = txtDestDir.Text;

if( strSourceDir[strSourceDir.Length-1] != '\\' )

strSourceDir += @"\";

if( strDestDir[strDestDir.Length-1] != '\\' )

strDestDir += @"\";

if( !CopyDirExt( strSourceDir, strDestDir ) )

MessageBox.Show( "Directory copied failed!" );

else

MessageBox.Show( "Directory copied successfully!" );

注意,我的CopyDirExt函数中的目录,是以“\”结束,因此要调用之前,需要根据需要进行补加字符“\”。

本文来自CSDN博客:http://blog.csdn.net/Knight94/archive/2006/03/27/640153.aspx