Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File is being used 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'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?

like image 281
frenchie Avatar asked Aug 14 '14 16:08

frenchie


People also ask

How do you fix the process Cannot access the file because it is being used by another process in C#?

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.

What does file WriteAllText do?

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.


2 Answers

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.

like image 129
Chris Avatar answered Oct 11 '22 22:10

Chris


Try this. During file creation, if any stream is opened, it will be closed.

FileStream stream = File.Create(TheFileJS);
stream.Close();
like image 3
John Stephen Avatar answered Oct 11 '22 22:10

John Stephen