将文件夹中的文件安全地复制到另一个文件夹

时间:2016-10-11 08:45:01

标签: c# .net thread-safety

我想做一个程序,将文件从一个文件夹复制到另一个文件夹,并将其分为YYYY / MM / DD等子文件夹。现在我已经完成了这个并且与观察者一起在后台执行此操作(因此每次创建新文件时都会复制它)

如何保证所有这些线程安全,以便程序可以等待5秒直到创建新文件并在此之后复制它?我的老板告诉我用System.Collections.Concurrent.ConcurrentQueue。

来做
public static void Main()   
{
    Run();
}

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{

    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = @"C:\tmp";

    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;

    watcher.Filter = "*.png";

    watcher.Created += new FileSystemEventHandler(OnCreated);

    watcher.EnableRaisingEvents = true;

    Console.WriteLine("Press \'q\' to quit the sample.");
    while (Console.Read() != 'q') ;
}

private static void OnCreated(object source, FileSystemEventArgs e)
{       
    Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);

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



    foreach (var file in new DirectoryInfo(sourcePath).GetFiles(fileName))
    {
        try
        {
            string dt = file.CreationTime.Day.ToString();
            string mn = file.CreationTime.Month.ToString();
            string yr = file.CreationTime.Year.ToString();

            var targetFolderName = String.Format(@"U:\{0:}\{1:}\{2:}", yr, mn, dt);
            var dir = Directory.CreateDirectory(targetFolderName);
            file.CopyTo(Path.Combine(dir.FullName, file.Name), true);
         }
         catch { }

     }
 } 

0 个答案:

没有答案