首页 > Linux操作系统 > Linux操作系统 > [转载]用C#实现目录拷贝
在C#中没有直接的目录拷贝函数,所以需要遍历源目录,然后逐个目录和逐个文件进行拷贝。以下就是实现代码:
///
/// Copy files from souce directory to dest directory
///
///
///
///
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;
}
///
/// Copy sub-directories and files from directory to dest directory
///
///
///
///
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函数中的目录,是以“”结束,因此要调用之前,需要根据需要进行补加字符“”。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/374079/viewspace-130576/ ,如需转载,请注明出处,否则将追究法律责任。