Tuesday, December 21, 2010

File Lock Problem in Visual Studio 2010 Build

I have been banging my head against my padded cubicle wall for several days now in frustration over a build error that keeps popping up in Visual Studio 2010.  When attempting to debug, or even just build without launching the debugger, I keep getting an error that looks like this:

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

For the first couple of days, I just grumbled angrily to myself and restarted Visual Studio whenever this happened, which it did not do consistently.  Sometimes it would work correctly for dozens of build/debug sessions, only to pop up at random times seemingly chosen to maximize my irritation.

Anyway, I did some searching around, and this is a fairly common complaint, with a fairly simple workaround.  I actually saw several different approaches to this, but the most elegant was the one I found here.  His sample assumes you are writing Visual Studio add-ins, but his fix works for Web Site projects, and should work for other project types as well.  I won't go through explaining the details of this problem, as the post linked above does a good job of that, but I will provide the fix here.  Simply add the following lines of code to the pre-build event command line of your project (the linked post provides a screenshot of what this look like in Visual Studio):


if exist "$(TargetPath).locked" del "$(TargetPath).locked"
if exist "$(TargetPath)" if not exist "$(TargetPath).locked" move "$(TargetPath)" "$(TargetPath).locked"