Check if file exists for 20 seconds C #

0

I'm doing a module that works with file sharing and in the documentation it asks to wait 20 seconds for the status file xxxxxxxx.sta, however, I'm not sure how to implement this in C #. I was trying something on this line, but it seems to run asynchronously, so I can not get the bool result if the file exists or not at the time I want:

public void ValidarArquivoStatus(int numeroSequencialDoArquivo)
{
    seq = numeroSequencialDoArquivo;
    aTimer = new Timer(1000);
    aTimer.Elapsed += OnTimedEvent;
    aTimer.AutoReset = true;
    aTimer.Enabled = true;

}

private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    Principal.ValidouArquivoDeStatus = false;
    previousTime = e.SignalTime;
    //int tempoMaximoTentativaExecucao = Convert.ToInt32(Funcoes.LeParametro(14, "7", false));
    int tempoMaximoTentativaExecucao = 20; 
    if (ExisteArquivoDeStatus(seq))
    {
        //aTimer.Enabled = false;
        Principal.ValidouArquivoDeStatus = true;
        aTimer.Enabled = false;
    }
    nEventsFired++;
    if ((nEventsFired == tempoMaximoTentativaExecucao) || (Principal.ValidouArquivoDeStatus == true))
    {
        aTimer.Enabled = false;
    }
}
    
asked by anonymous 21.08.2017 / 20:23

2 answers

1

Given that your validation method is not asynchronous, I'll assume you need to check every 20 seconds for a file in a given directory.

Following your line of reasoning, the code below executes the method DoWork() through timer_Elapsed .

At the end of DoWork() execution, the timer is "restarted" ( finally ) and DoWork() is called again.

using System;
using System.Timers;

namespace LearnTemporizador
{
    class Program
    {
        private static Timer timer;

        static void Main(string[] args)
        {
            timer = new Timer();

            timer.Elapsed += timer_Elapsed;

            timer.AutoReset = false;

            timer.Enabled = true;

            timer.Interval = TimeSpan.FromSeconds(20).TotalMilliseconds;

            timer.Start();

            Console.ReadKey();
        }

        private static void DoWork()
        {
            Console.WriteLine($"Validou! {Validar()}");
        }

        private static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                DoWork();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                timer.Start();
            }
        }

        private static bool Validar()
        {
            return true;
        }
    }
}
    
21.08.2017 / 21:47
0

If it's just to wait for this time, you can use the thread's timer.

just add the code below before the file check:

Thread.Sleep(20000);

Note: If you are not using it, you need to import it below:

using System.Threading;
    
21.08.2017 / 20:32