簡體   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