To implement retry logic when reading a file that may be
temporarily unavailable (e.g., locked by another process), you can use a
try-catch loop with delays and retry limits.
Example: Retry File Read with Delay
using System;
using System.IO;
using System.Threading;
class FileReadWithRetry
{
public static string ReadFileWithRetries(string filePath, int maxRetries = 5, int delayMs = 1000)
{
int attempt = 0;
while (true)
{
try
{
// Attempt to read the file
using (FileStream stream = new FileStream(
filePath,
FileMode.Open,
FileAccess.Read,
FileShare.Read)) // Adjust sharing mode as needed
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
catch (IOException ex)
{
attempt++;
if (attempt >= maxRetries)
throw new IOException($"Failed to read file after {maxRetries} attempts.", ex);
Console.WriteLine($"File is unavailable (attempt {attempt}), retrying in {delayMs} ms...");
Thread.Sleep(delayMs);
}
}
}
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To implement retry logic when reading a file that may be temporarily unavailable (e.g., locked by another process), you can use a
try-catchloop with delays and retry limits.Example: Retry File Read with Delay
Usage
Parameters You Can Tune
maxRetries: How many times to retry.delayMs: Milliseconds to wait between attempts.FileShare.ReadtoFileShare.Noneif you need exclusive access.Best Practices
Task.Delay()withasync/awaitinstead ofThread.Sleep.Read More