How do I wait for the file to be free so that ss.Save() can overwrite it with a new one? If I run this twice close together(ish), I get a generic GDI+
If you check access before writing to the file some other process might snatch the access again before you manage to do your write. Therefor I would suggest one of the following two:
getting a stream
private FileStream GetWriteStream(string path, int timeoutMs)
{
var time = Stopwatch.StartNew();
while (time.ElapsedMilliseconds < timeoutMs)
{
try
{
return new FileStream(path, FileMode.Create, FileAccess.Write);
}
catch (IOException e)
{
// access error
if (e.HResult != -2147024864)
throw;
}
}
throw new TimeoutException($"Failed to get a write handle to {path} within {timeoutMs}ms.");
}
then use it like this:
using (var stream = GetWriteStream("path"))
{
using (var writer = new StreamWriter(stream))
writer.Write("test");
}
retry scope
private void WithRetry(Action action, int timeoutMs = 1000)
{
var time = Stopwatch.StartNew();
while(time.ElapsedMilliseconds < timeoutMs)
{
try
{
action();
return;
}
catch (IOException e)
{
// access error
if (e.HResult != -2147024864)
throw;
}
}
throw new Exception("Failed perform action within allotted time.");
}
and then use WithRetry(() => File.WriteAllText(Path.Combine(_directory, name), contents));