关闭

[愚翁专栏]用C#实现目录拷贝

1011人阅读 评论(0) 收藏 举报

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函数中的目录,是以“/”结束,因此要调用之前,需要根据需要进行补加字符“/”。


0
0

  相关文章推荐
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:311081次
    • 积分:4308
    • 等级:
    • 排名:第7277名
    • 原创:79篇
    • 转载:33篇
    • 译文:55篇
    • 评论:103条
    文章分类
    最新评论