[愚翁专栏]用C#实现目录拷贝
来源:互联网 发布:java趣味编程100例视频 编辑:程序博客网 时间:2024/04/27 13:57
在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函数中的目录,是以“/”结束,因此要调用之前,需要根据需要进行补加字符“/”。
- [愚翁专栏]用C#实现目录拷贝
- 用C#实现目录拷贝
- 用C#实现文件夹拷贝
- 用Python 实现的目录拷贝程序
- Java 实现目录拷贝
- C# 多线程目录拷贝 文件拷贝
- c#实现深浅拷贝
- 实现多线程拷贝多级目录
- linux c 实现目录拷贝
- 目录拷贝–bash实现
- python实现文件夹目录拷贝
- linux 目录拷贝程序实现
- [愚翁专栏]图像旋转的C#示例
- 实现目录拷贝 复制目录 复制文件
- C#下获取目录移动目录拷贝目录
- C# 拷贝文件到另一个目录
- C# 拷贝文件夹到指定目录
- 愚翁专栏学习
- 实现google baidu yahoo soso ... 站内搜索代码
- 模擬退火法
- [愚翁专栏]如何用C#写一个简单的Login窗口
- 跳出来!跳出来!
- [愚翁专栏]如何用C#做一个悬浮窗口程序
- [愚翁专栏]用C#实现目录拷贝
- Exceptional C++ Style之27
- [愚翁专栏]图像旋转的C#示例
- 近期的部分经典摘句与读书笔记
- [愚翁专栏]如何把多个文件写入到一个文件中去并能分解
- [愚翁专栏]如何用C#做一个类似于桌面插件的程序
- AIO SN + Crack Searching by p0k
- 表格 隔行颜色不同 Css
- 台风过后的思考