Delta Engine Blog

All about multiplatform and game development

Quick Tip: Getting rid of the "Unable to copy file" error in Visual Studio

I had often the problem that after a while of using Visual Studio 2005 (especially in beta) and now with Visual Studio Orcas that when the solution grows and grows to many projects you encounter the following error quite often:

Unable to copy file "obj\Debug\<projectname>.dll" to "bin\Debug\<projectname>.dll".

The process cannot access the file 'bin\Debug\<projectname>.dll' because it is being used by another process.

This can be caused if you have not closed the app yet or use the dll/exe somewhere or even if a unit test is still running and does not quit. But these cases are not the problem, that is easily fixed by killing the process. More often this is caused by some bug in Visual Studio. Some designer locked the file, some resource was not released, etc.
The usual "solution" to this problem was to close Visual Studio and start it up again, then it worked for a while until you end up with the same issue. Just having 2-3 projects in a solution is not very problematic because this error just occurs once in a while. With 5+ projects and using a lot of unit testing, starting tests all over the place, and compiling every couple of minutes (or seconds) this is really an annoying problem that can slow you down.

The easy fix is to delete the <projectname>.dll.locked file in the bin\Debug\ directory, after that compiling works again and it can copy the file now.
A better and more clever solution is to add the following lines to each Pre-Build-Events texbox in each project:

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

After doing that no more "Unable to copy file" errors anymore :)

BTW: My last attempt to polynap recently (1.5 hours sleep every 6 hours) failed after doing it for about a week, have to find a better schedule, maybe every 4 hours was a better idea because it was more strict.