Visual Studio might throw the error “Unable to copy file ‘objx86Debugfile.exe’ to ‘binDebugfile.exe’. The process cannot access the file ‘binDebugfile.exe’ because it is being used by another process” to you one fine day and leave you wondering how to get rid of it.
It is actually Visual Studio itself that is keeping the file open, and a subsequent project build cannot overwrite it. Also, there is seemingly no cause. The error just happens, and then refuses to go away until you restart Visual Studio, which will cause the lock on the file to go away.
The internet is full of fixes for this error, typically involving pre-build scripts that try to delete the locked .exe file so that the build process can finish, or using the task manager (or ProcessExplorer) to kill the Visual Studio debug hosting process. However, this is just fighting symptoms. There should be an actual point where this error starts to happen, and we should undo whatever we did then to make the error stop occurring.
In my experience, there is in fact a cause. For me, the error started to occur after I had made a small change to my project’s AssemblyInfo.cs:
This is because I wanted automatic version numbering. The original AssemblyInfo.cs will contain this line:
Now if you replace the last two digits of the assembly version with an asterisk, then Visual Studio will replace it with new values each time you build. The values it uses are actually based on the current date and time. This seems useful, since now you won’t be stuck with version 220.127.116.11 and Visual Studio increments versions each time you build, so you don’t have to do this manually.
However: Danger, Will Robinson, Danger! It seems to me that this automatic version numbering is actually the culprit behind the “cannot access the file” error. Apparently Visual Studio will keep track of generated executables, perhaps in an effort to increase the version number when you build a new one. Get rid of it and your file access problem goes away. In this instance, you’re really better off updating the version numbers yourself, or adding a plugin to Visual Studio that does it for you.