I have a part of my code that writes to a text file. This is the only process active that is supposed to write to the file, and here is how it's done:
try
{
File.AppendAllText(path, '\n' + tmp);
}
catch (Exception)
{
lblError.Text = "Unable to save file";
}
This works fine like half of the time. But sometimes it throws an exception saying that the file is being used by another process. I looked up what process uses the file, and its w3wp.exe
. I've read that File.AppendAllText
closes the file once it's done with it, so it should be fine like I've done it. Right?
EDIT:
Description of purpose was requested, so here goes. This part of the code is supposed to append a line to a config textfile that another process will use. I am 100% certain that that process isn't currently running.
I might also add that this is an asp.net application (from code behind). So a user can write to config.txt from an asp-page.
I've tried this:
static readonly object saveLock = new object();
/*
* stuff
*/
protected void saveToConfig(string input)
{
lock(saveLock)
{
File.AppendAllText(path, '\n' + input);
}
}
But I still get the IOException-error saying that multiple processes are trying to access the file.
You could use Palmer to create some logic, which repeats the write if it fails:
Retry.On<IoException>().For(TimeSpan.FromSeconds(15)).With(context =>
{
File.AppendAllText(path, '\n' + tmp);
});