Can not copy... Visual Studio error.

A common problem with Visual Studio is that it leaves locks in place inappropriately after debugging. A quick search for

visual studio 2010 "unable to copy file"

will show how prevalent the problem is.

This workaround was suggested for building add-ins, but it works for WinForm applications as well: File Lock Issue in Visual Studio When Building a Project.

The basic idea is to add a few lines to your Pre-build event:

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

The idea is to dump the .locked directory then move the existing files to .locked. Frankly, I am surprised that locked files can be moved like this, but these lines have saved me much frustration with Visual Studio since I found this fix.