2016-10-10 259 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); 
} 
相关问题