编程语言
首页 > 编程语言> > C# 文件夹的复制

C# 文件夹的复制

作者:互联网

指定文件夹的复制(包括文件夹内的所有文件),最后一个bool参数表示:如果可以覆盖目标文件,则为 true;否则为 false。

private bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)
        {
            bool ret = false;
            try
            {
                SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
                DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";

                if (Directory.Exists(SourcePath))
                {
                    if (Directory.Exists(DestinationPath) == false)
                        Directory.CreateDirectory(DestinationPath);
                    else
                    {
                        MessageBox.Show("文件已存在...!", "提示:");
                        return false;
                    }

                    foreach (string fls in Directory.GetFiles(SourcePath))
                    {
                        FileInfo flinfo = new FileInfo(fls);
                        flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
                    }
                    foreach (string drs in Directory.GetDirectories(SourcePath))
                    {
                        DirectoryInfo drinfo = new DirectoryInfo(drs);
                        if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false)
                            ret = false;
                    }
                }
                else
                {
                    MessageBox.Show("文件不存在...!", "提示:");
                    return false;
                }
                ret = true;
            }
            catch (Exception ex)
            {
                ret = false;
            }
            return ret;
        }
Danny_¥%#* 发布了51 篇原创文章 · 获赞 5 · 访问量 1万+ 私信 关注

标签:false,C#,ret,SourcePath,DestinationPath,文件夹,bool,复制,Directory
来源: https://blog.csdn.net/qq_43024228/article/details/104532811