簡體   English   中英

如何使用C#從一個路徑復制文件夾並將其粘貼到另一路徑?

[英]How to copy a folder from one one path and paste it to another path using C#?

復制的原始文件夾應粘貼到以今天的日期命名的文件夾中,例如“ 220310”

喜歡.....

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

目標文件夾:D:// Dest / 220310 / AbcFolder

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;
        }

基本上你會用

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

獲取要復制的所有文件,然后通過以下方式創建目標目錄

Directory.Create(destinationFolder)

並遍歷原始文件名(在files中 ),使用FileInfo類獲取原始文件的路徑,並使用File.Copy()將文件復制到新位置。 所有這些類都在System.IO命名空間中。

您可以通過以下方式獲取日期時間:

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

有關將目錄復制到另一個的信息,請參見此CodeProject文章: 將目錄復制到另一個位置的功能(沒有花哨的地方)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM