繁体   English   中英

如果给定路径中存在文件,则每秒检查一次计时器

[英]Check with a timer every second, if a file exist in a given path

我有一个用C#编写的简单控制台应用程序,我在其中创建了一个zip文件。 从另一个控制台应用程序,我让计时器每秒打勾,以检查我在第一个应用程序中创建.zip文件的目录是否包含.zip文件,但它不起作用。

我实现了代码:

public class Program
{
    private static System.Timers.Timer aTimer;
    private static String path = "C:\\Path\\*.zip";

    public static void Main()
    {
        SetTimer();

        Console.WriteLine("\nChecking the ZIP file is created on the directory...\n");
        Console.WriteLine("The application started at {0:HH:mm:ss}", DateTime.Now);
        Console.ReadLine();


    }

    private static void SetTimer()
    {
        if (!File.Exists(path))
        {
            // Create a timer with a two second interval.
            aTimer = new System.Timers.Timer(1000);
            // Hook up the Elapsed event for the timer. 
            aTimer.Elapsed += OnTimedEvent;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;
        }
        else
        {
            Console.WriteLine("ZIP file created.");
            aTimer.Stop();
            aTimer.Dispose();

            Console.WriteLine("Terminating the application...");
        }     
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss}",
                          e.SignalTime);
    }


}

有人可以帮帮我吗? 谢谢!

File.Exists不支持像*这样的通用通配符

甚至, FileSystemWatcher是执行此类任务的更好方法,您可以立即使用它来解决您的问题

   if (!new DirectoryInfo("c:\\path").EnumerateFiles("*.zip").Any())
    {
        // Create a timer with a two second interval.
        aTimer = new System.Timers.Timer(1000);
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM