2016-10-10 258 views
0

我想將所有照片從一個文件夾重新組織到另一個路徑的子文件夾中,我想在其中創建以文件創建日期命名的新子文件夾。嘗試將子文件夾中的文件從一個文件夾移動到另一個文件夾C#

實施例:

photo1.png(創建日期2015年2月12日)

photo2.png(創建日期2015年2月12日)

photo3.png(創建日期2015年2月13日)

- >創建兩個子文件夾: 「12-FEB-2015」 與photo1.png和photo2.png和 「13-FEB-2015」 與photo3.png

我編寫了將照片複製到其他文件夾並使用當前日期創建子文件夾的代碼。但我不知道如何創建以文件創建日期命名的子文件夾。

public class SimpleFileCopy 
{ 
    static void Main(string[] args) 
    { 
     // Specify what is done when a file is changed, created, or deleted. 
     string fileName = "*.png"; 
     string sourcePath = @"C:\tmp"; 
     string targetPath = @"U:\\"; 

     // Use Path class to manipulate file and directory paths. 
     string sourceFile = Path.Combine(sourcePath, fileName); 
     //string destFile = Path.Combine(Directory.CreateDirectory("U:\\" + DateTime.Now.ToString("dd-MMM-yyyy") , fileName); 

     // To copy a folder's contents to a new location: 
     // Create a new target folder, if necessary. 
     if (!Directory.Exists("U:\\" + Directory.CreateDirectory("U:\\" + DateTime.Now.ToString("dd-MMM-yyyy")))) 

     { 
      Directory.CreateDirectory("U:\\" + Directory.CreateDirectory("U:\\" + DateTime.Now.ToString("dd-MMM-yyyy"))); 
     } 
     else 
     // To copy a file to another location and 
     // overwrite the destination file if it already exists. 
     { 

      foreach (var file in new DirectoryInfo(sourcePath).GetFiles(fileName)) 
      { 
       try 
       { 
        file.CopyTo(e.FullPath.Combine(targetPath + Directory.CreateDirectory("U:\\" + DateTime.Now.ToString("dd-MMM-yyyy")), file.Name)); 
       } 
       catch { } 
      } 
     } 
    } 
} 
+0

的可能的複製[如果文件夾不存在,則創建(http://stackoverflow.com/questions/9065598/if-a-folder-does-not-exist-create-it) – Liam

+0

等待那裏......你已經創建的目錄?你的問題沒有道理呢?你究竟在幹什麼? – Liam

+0

您正在創建基於DateTime.Now的dirs,這是您的問題的基礎? –

回答

0

您正在通往許多Directory.CreateDirectory調用。只需枚舉源文件夾文件,然後獲取日期file.CreationTime,請致電Directory.CreateDirectory(不管它是否已存在),然後複製您的文件。

string fileName = "*.png"; 
string sourcePath = @"C:\tmp"; 
string targetPath = @"U:\"; 

foreach (var file in new DirectoryInfo(sourcePath).GetFiles(fileName)) 
{ 
    var targetFolderName = file.CreationTime.ToString("dd-MMM-yyyy"); 
    var dir = Directory.CreateDirectory(Path.Combine(targetPath, targetFolderName)); 
    file.CopyTo(Path.Combine(dir.FullName, file.Name), true); 
} 
相關問題