The file is in use by another process when using File.WriteAllText

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 use File.WriteAllText

it because I thought it would prevent file locking problems, but it happens that sometimes I get an error File is being used by another process

. The problem is that it is rare , but once this exception occurs in a specific file, all client calls to that file then result in a 404.

What do I need to change in my code to make sure this error never happens?

Thank.

+3


source to share


2 answers


I would suggest that you are having problems with a lock that remains open after deletion, which prevents you from overwriting the file.

The good news is that this can be easily resolved without deleting the file in the first place.

In the docs for,WriteAllText

it says, "Creates a new file, writes the specified line to the file, and closes the file. If the target file already exists, it is overwritten."



This means that it actually deletes the contents of the file anyway, so checking if the file exists first is unnecessary. If you don't do this check, you shouldn't run into any problems.

In this case, exception handling will be helpful. If this is critical code, you can try again, or alert the admin immediately about an issue that will hopefully prevent all of your clients then 404.

+5


source


Try it. On creation file

, if any stream

opens, it will be closed.



FileStream stream = File.Create(TheFileJS);
stream.Close();

      

+3


source







All Articles