2016-10-10 4 views
0

1つのフォルダのすべての写真を、別のパスのサブフォルダに再編成したい場合、ファイルの作成日を指定して新しいサブフォルダを作成します。サブフォルダを使用してあるフォルダから別のフォルダにファイルを移動しようとしています。C#

例:

photo1.png(作成日2015年2月12日)

photo2.png(作成日2015年2月12日)

photo3.png(作成日2015年2月13日)

- > 2つのサブフォルダを作成する: "12年02月 - 2015" photo1.pngとphoto2.pngと "13年02月-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); 
} 
関連する問題