2016-10-10 5 views
0

한 폴더의 모든 사진을 다른 경로의 하위 폴더로 재구성하려는 경우 파일 생성 날짜로 이름이 지정된 새 하위 폴더를 만들고 싶습니다.하위 폴더가있는 한 폴더에서 다른 폴더로 파일을 이동하려고합니다. C#

예 :

photo1.png (작성일 2015년 2월 12일)

photo2.png (작성일 2015년 2월 12일)

photo3.png (작성일 2015년 2월 13일)

-> 두 개의 하위 폴더를 작성 "2 월 12-2015"과 photo1.png photo2.png 및 "2 월 13 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를 기반으로 디렉토리를 만들고 있습니다. 질문의 기초가 무엇입니까? –

답변

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