The snippet of code was just supposed to write a string into a text file called \"all_results.txt\". I had errors implementing in File.WriteAllText. After searching the net
I found the post while I had similar problem. The given advises gave me an idea! So for this purpose I wrote the following method
public static void ExecuteWithFailOver(Action toDo, string fileName)
{
for (var i = 1; i <= MaxAttempts; i++)
{
try
{
toDo();
return;
}
catch (IOException ex)
{
Logger.Warn("File IO operation is failed. (File name: {0}, Reason: {1})", fileName, ex.Message);
Logger.Warn("Repeat in {0} milliseconds.", i * 500);
if (i < MaxAttempts)
Thread.Sleep(500 * i);
}
}
throw new IOException(string.Format(CultureInfo.InvariantCulture,
"Failed to process file. (File name: {0})",
fileName));
}
then I used the method in the following way
Action toDo = () =>
{
if (File.Exists(fileName))
File.SetAttributes(fileName, FileAttributes.Normal);
File.WriteAllText(
fileName,
content,
Encoding.UTF8
);
};
ExecuteWithFailOver(toDo, fileName);
Later analyzing the logs I have discovered that the reason of my troubles was an attempt to act against the same file from the parallel threads. But I still see some pro-s in using the suggested FailOver method