【问题标题】:How to copy a folder from one one path and paste it to another path using C#?如何使用 C# 从一个路径复制文件夹并将其粘贴到另一个路径?
【发布时间】:2010-03-22 07:45:26
【问题描述】:

复制的原始文件夹应粘贴在以今天日期命名的文件夹中,例如“220310”

喜欢.....

原始文件夹:c://Org/AbcFolder

目标文件夹:D://Dest/220310/AbcFolder

【问题讨论】:

    标签: c#


    【解决方案1】:
    private static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)
            {
                bool ret = true;
                try
                {
                    SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
                    DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";
    
                    if (Directory.Exists(SourcePath))
                    {
                        if (Directory.Exists(DestinationPath) == false)
                            Directory.CreateDirectory(DestinationPath);
    
                        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;
                        }
                        Directory.CreateDirectory(DI_Target + "//Database");
                    }
                    else
                    {
                        ret = false;
                    }
                }
                catch (Exception ex)
                {
                    ret = false;
                }
                return ret;
            }
    

    【讨论】:

    • 看起来这是一个额外的行Directory.CreateDirectory(DI_Target + "//Database");
    【解决方案2】:

    基本上你会使用

    var files = Directory.GetFiles(originalFolder,"*.*",SearchOption.AllDirectories) 
    

    获取要复制的所有文件,然后通过

    创建目标目录
    Directory.Create(destinationFolder)
    

    并遍历原始文件名(在 files 中),使用 FileInfo 类获取原始文件的路径,以及 File.Copy()将文件复制到新位置。 所有这些类都在 System.IO 命名空间中。

    【讨论】:

      【解决方案3】:

      你可以用这个来获取日期时间:

      DateTime dtnow = DateTime.Now;
      string strDate=dtnow.Day.ToString()+dtnow.Month.ToString()+dtnow.Year.ToString();
      

      要将目录复制到另一个目录,请参阅这篇 CodeProject 文章:Function to copy a directory to another place (nothing fancy)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-29
        • 1970-01-01
        • 2010-12-31
        • 1970-01-01
        • 2012-08-02
        • 2011-08-10
        • 1970-01-01
        相关资源
        最近更新 更多