Build error: "The process cannot access the file because it is being used by another process"

I've got a C# webforms app, that until today had been working just swimmingly.

Now today, all of a sudden, every time I try run the app, I get a file locking error:

Unable to copy file "obj\Debug\MyProject.exe" to "bin\Debug\MyProject.exe". The process cannot access the file "bin\Debug\MyProject.exe" because it is being used by another process.

Googling the error doesn't come up with anything beyond the obvious, i.e. VS thinks the file is locked. And it is definitely Visual Studio itself that locks the file, because when I close VS and reopen it, the project executes fine - the first time. When I try to run it a second time, I get the file locking error.

Closing VS and reopening every time I want to run the app is not a viable workaround! How do I find out what's locking the file, and stop it from getting locked?

EDIT: Another interesting discovery: I don't even have to run the app. Just compiling it once causes the file locking; I cannot compile twice in a row!

This problem is specific to one project in my solution. All other projects work fine and can be executed as many times as I like. It's only this one project that gets itself locked up.


Solution 1:

I have found a simple solution which works for me. It goes like this:

When the problem occurs, just change the building configuration at the top (if in “Release” to “Debug” and vice versa), build and then change back to previous configuration and build again.

screenshot

I suppose that changing the configuration releases the vcshost and devenv.

Solution 2:

Well, I solved the problem myself - though I still have no clue why. I decided to isolate the problem by removing all files from the project, then re-adding them and determining that way which file was the source of my trouble. So, one by one I reintroduced files to the project, compiled & cleaned each step of the way... until... I added the last one...

... and everything still worked fine.

I did a compare to the source control of my original .csproj; no real differences. And even when I tried reverting to the previous version of the .csproj, it still worked.

Black magic. If it works, sometimes it's better not to ask why - just accept it and move on...

EDIT: The problem is a recurring one, and I believe I've isolated it to when I have the form designer open of an abstract/generic form at compile time.

Lesson learned: Make sure the Form Designer of any abstract or generic forms or controls is closed before you compile! If not, you have to close VS and reopen!

Solution 3:

What we have discovered here, is the following: In the project properties page, Debug tab, uncheck the "Enable visual studio hosting process". I am unsure what this property is for, but it does the work once unchecked.

Solution 4:

VS2017 - Solved by closing all instances of MSBuild.exe in the windows task manager