user1550951
user1550951

Reputation: 379

Check number of times if file is ready

I am printing a PrintDocument to PDF.I then store this PDF in a MS SQL table.I have to make sure the document is "printed" before I insert it into a column.I have the following code to check if a file is "available":

public static bool IsFileReady(String sFilename)
{
    try
    {
         using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
         {
              if (inputStream.Length > 0)
              {
                  return true;
              }
              else
              {
                   return false;
              }
          }
    }
    catch (Exception)
    {
          return false;
    }
}

I want to add some sort of upper limit to either the time it takes or the number of times it checks if the file is ready. If the printer fails then the thread will keep waiting forever. How do I implement it?

Upvotes: 0

Views: 163

Answers (1)

PJSimon
PJSimon

Reputation: 343

This code exits the loop if the max retries is reached OR the max time has elapsed:

    private const int MAX_RETRIES = 100;
    private const int MAX_RETRY_SECONDS = 120;
    public static bool IsFileReady(String sFilename)
    {
        int tryNumber = 0;
        DateTime endTime = DateTime.Now + new TimeSpan(0, 0, MAX_RETRY_SECONDS);

        while (tryNumber < MAX_RETRIES && DateTime.Now < endTime)
        {
            try
            {
                using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    if (inputStream.Length > 0)
                    {
                        return true;
                    }
                }
            }
            catch (Exception)
            {
                //Swallow Exception
            }

            //Slow down the looping 
            System.Threading.Thread.Sleep(500);

            tryNumber += 1;
        }

        return false;
    }

Upvotes: 2

Related Questions