int retryCount = 0; bool fileOpenedSuccessfully = false; while (!fileOpenedSuccessfully && retryCount < maxRetries) { try { using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read, FileShare.None)) { fileOpenedSuccessfully = true; } //if (!IsFileLocked(imagePath)) //{ // fileOpenedSuccessfully = true; //} } catch (Exception ex) { Console.WriteLine($"Exception: {ex.GetType().Name}, Message: {ex.Message}"); Thread.Sleep(retryDelayMilliseconds); retryCount++; } } if (fileOpenedSuccessfully) { .....