I have some code that saves a string to a file, something like this:
string TheFileJS = HttpRuntime.AppDomainAppPath + "\\SomePath\\" + ClientFileName + ".js";
if (File.Exists(TheFileJS) == true)
{
File.Delete(TheFileJS);
}
File.WriteAllText(TheFileJS, TheJS);
I'm using File.WriteAllText
because I thought it would prevent problems with file locking but what's happening is that sometimes I get the error File is being used by another process
. The problem is that it rarely happens, but once this exception occurs on a particular file, all client calls to this file then result in a 404.
What do I need to change in my code to make sure this error never happens?
Process cannot access file because it is being used by another process error message. To resolve this error: Press Ctrl + Alt + Delete, then click Task Manager. Ensure you're on the Processes tab.
WriteAllText(String, String, Encoding) Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.
I would imagine that you are running into problems with the lock still being open after the delete causing you to be unable to then rewrite the file.
The good news is that this is easily solvable by not deleting the file first.
From the docs for WriteAllText
it says "Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten."
What this means is that it effectively deletes the contents of the file anyway so checking if the file exists first is unnecessary. If you are not doing that check then you shouldn't run into any problems.
This is also where exception handling would come in handy. If this is critical code then you could retry or alert an admin immediately of the problem hopefully preventing all your clients then 404ing.
Try this. During file
creation, if any stream
is opened, it will be closed.
FileStream stream = File.Create(TheFileJS);
stream.Close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With