425

I keep getting this error during the build of my VS2012 C# project

Error   41  Could not copy "obj\Debug\WeinGartner.WeinCad.exe" to
 "bin\Debug\WeinGartner.WeinCad.exe". 
 Exceeded retry count of 10. Failed.    


Error   42  Unable to copy file "obj\Debug\WeinGartner.WeinCad.exe" to
"bin\Debug\WeinGartner.WeinCad.exe". The process cannot access the file
'bin\Debug\WeinGartner.WeinCad.exe' because it is being used by another 
process.    

Now I've figured out that killing the process

Weingartner.WeinCad.vhost.exe

works (sometimes ) but this is getting on my nerves. Any way to stop this happening at all?

My debugger settings are

enter image description here enter image description here

Ogglas
  • 62,132
  • 37
  • 328
  • 418
bradgonesurfing
  • 30,949
  • 17
  • 114
  • 217
  • For me it was caused by manually launched .exe in the Release directory. The problem was that VS cannot copy over an executable that is still running. I'll try to fix it with properly cleaning up resources so the program does not leave hanging after window close button. – lahjaton_j Jan 08 '16 at 08:24
  • There is a good summary of this problem with typical steps to resolve in [this question](https://stackoverflow.com/q/2895898/6501141) – LightCC Oct 06 '17 at 17:57
  • This was happening for me because Windows Defender decided it no longer liked the .exe from the VS2019 project upon which I am working. Been working on this for weeks with no issue but today, guess a new update didn't like it. Had to exclude my Source folders. Stopped happening. – AdvApp Jan 30 '20 at 21:48

69 Answers69

518

I have encountered similar error messages in Visual Studio 2013.

Mostly, I have found that this situation has occurred when a debug process was halted because of an exception.

When clean+build has not resolved this problem for me, I have had success by doing the following:

  • Closing Visual Studio
  • Deleting the bin and obj folders, and
  • Reopening Visual Studio.

This "bug" has existed since Visual Studio 2003.

Finally, I have also found that I can often overcome this problem by simply renaming the executable file and then deleting it.

DavidRR
  • 18,291
  • 25
  • 109
  • 191
Gerard
  • 13,023
  • 14
  • 72
  • 125
  • 76
    This is not a solution, at the best a partial solution. I dont wanna restart VS every 10min. Cleaning the solution works for me, but cleaning it every 10min is also not a solution. – Legends Apr 15 '15 at 19:39
  • 8
    From my experience, VS2013 does this at least 10 times a day for me no matter what machine I am developing on. It's like the bug has gotten worse. Just sayin' – A.R. May 07 '15 at 21:16
  • Removing the Bin and Obj folder did it for me! I actually got an error in the team explorer when I deleted one of the build folders while having visual studio 2013 still open. I closed visual studio and deleted my bin, obj, and temp folders and the error disappeared. – Marvin Brouwer Sep 10 '15 at 10:04
  • Sometimes only restarting VS also works. Better try restarting it first. If it doesn't work, then delete the "bin" and "obj" folders. – Zafer Sernikli Jan 20 '16 at 12:24
  • Here is a script to get rid of this problem definitely! http://blog.ndepend.com/visual-studio-script-saves-time-pain/ – Patrick from NDepend team Mar 07 '16 at 10:57
  • I need to restart visual studio 2015 and remove bin folder every time a change in code on a project that is referenced to others in a solution with 41 projects. And it happens suddenly, so this really slow down my work very much.... First time I really don't like Visual Studio – Alexander Apr 15 '16 at 15:17
  • I closed VS and deleted the contents inside bin and obj and then restarted VS 2013 and it is fine ( VS 2015 overall is just nicer, but there are other vs 2015 issues that seem to mostly get resolved with a close and re-open) – Tom Stickel May 19 '16 at 17:52
  • Is there a setting to reduce the number retries that VS do when it happens? – mistika Dec 29 '16 at 17:57
  • 2
    I closed Visual Studio. Killed WcfHost.exe process. Deleted bin/obj folders of the project where error was occurring. Started VS and no more errors. – itsrizi Apr 17 '17 at 07:30
  • Did not work anything , i restart my machine and all works fine :) – Usman Younas May 04 '17 at 11:46
  • Let's put an end this annoying madness, please vote [here](https://developercommunity.visualstudio.com/content/problem/62419/building-multi-platform-solutions-has-become-a-nig.html) – Shimmy Weitzhandler May 29 '17 at 01:34
  • Still an issue with VS2017... What I do is that I end task on any MSBuild running. – François Jun 29 '17 at 10:50
  • @François in VS2017, I just found that I get this error when I forget that I am actually running the project in the command prompt. – Craig Jul 19 '17 at 09:12
  • 4
    Yeah... issue still exist sin 2017... pretty annoying. – Douglas Gaskell Jul 24 '17 at 04:28
  • 1
    Closing the app process from TaskManager solved my problem. :) – Naveen Kumar V May 15 '18 at 11:33
  • simply deleting the process Yout_Project_Name.exe can solve the problem. – MindRoasterMir Feb 05 '19 at 23:10
  • I tried the above steps but it didn't worked for me. After that i again did the same thing but this time i restarted the machine. Then the error was gone. I think there was some process which was blocking VS and giving the build error. After restart that process got stopped. – Indranil Feb 28 '19 at 05:25
  • I can confirm it still exists today in Visual Studio 2019, 16 years later. Which is pretty shocking really; thanks for your help! – Lee Apr 29 '19 at 14:42
  • 67
    bug still exist in VS 2019. – Akash KC May 14 '19 at 14:41
  • 1
    i fixed it in vs 2019, same mentioned procedures if you cant delete bin folder ,just rename it – hosam hemaily Nov 03 '19 at 00:13
  • I deleted the 2 directories + restarted my PC. – Tassisto Dec 06 '19 at 07:42
  • 2
    The .exe file of your application is a likely a suspended process, this means you will not be able to delete the file. If you end the suspended process in Resource Monitor, you will be able to delete the bin folder and build once again. – Jamie Feb 04 '20 at 09:38
  • I have had this error before and this is usually the solution, but not this time for me. Instead I copied the whole solution opened that instead. It worked! – Flemming Bonde Kentved Feb 10 '20 at 21:40
  • Open Visual Studio as Administor SOLVE all this kind of problems... – Masciuniria May 08 '20 at 09:20
  • 1
    Still happening in VS 2020 – Gustavo Jun 17 '20 at 22:32
  • 1
    @Vesper There is no VS 2020, it's still called VS 2019. – Tim567 Jun 25 '20 at 06:15
  • In my case, my web app process was still running. Like the bro above I killed it in task manager and that resolved the issue. Not sure what prevented VS from killing it. – tnk479 Sep 24 '20 at 21:04
  • This issue is discussed here as well - but with no solution: https://github.com/microsoft/vstest/issues/661 Absolutely annoying! – Matt Feb 01 '21 at 15:43
  • In my case, on VS 2019, VS was saying that other dlls that I locally had were the issue. After digging deeper, I I found that I was missing a different dll and needed to repair my VS 2019 installation. If possible, I'd recommend checking the ActivityLog.xml file under AppData\Roaming\Microsoft\VisualStudio to see what might be the root cause. – Chioke Aarhus May 20 '21 at 20:59
  • 1
    What solved the issue for me in VS 2019 is going to Task Manager and killing the .NET Host process. – Dima Shivrin Jul 05 '21 at 12:11
  • This solved some specflow issues for me – Charlie S Mar 11 '22 at 12:23
  • 5
    Getting this in VS 2022 as well. – ouflak Jan 16 '23 at 10:07
  • I can't believe this bug has not been fixed in 7 years. – elektra Feb 12 '23 at 14:56
112

In Visual Studio Premium 2013 (Update 3), I solved this with a pre-build one-liner:

(if exist "$(TargetDir)*old.pdb" del "$(TargetDir)*old.pdb") & (if exist "$(TargetDir)*.pdb" ren "$(TargetDir)*.pdb" *.old.pdb)

This gracefully deletes any old PDB files (if it can), then renames anything that's left with a .old.pdb extension. A nice side effect is that if the old PDB is still locked, it just adds another .old piece to the filename, and they all get cleaned up next time you restart Visual Studio and do a build.

For example, build/debug session 1 leaves MyProject.pdb locked.
The next time you build:
MyProject.pdb --> MyProject.old.pdb

Then, build/debug session 2 is started, and both MyProject.pdb and MyProject.old.pdb are still locked:
MyProject.old.pdb --> MyProject.old.old.pdb
MyProject.pdb --> MyProject.old.pdb

Finally, restarting Visual Studio and doing a fresh build will get rid of both of these, and continue the process as usual.

Geoff
  • 8,551
  • 1
  • 43
  • 50
  • 5
    The same in VS2010, VS 2012 – Boogier Jan 16 '15 at 06:26
  • 7
    Thank you, worked perfectly for me with modifying your example to using exe files instead. I think this might be a bug in the latest VS 2015 CTP as well. – Johny Skovdal Feb 22 '15 at 20:55
  • Glad it helped - I still have my pre-build command set up, and it works well enough that I'd forgotten it was there! – Geoff Feb 22 '15 at 21:08
  • 3
    I hate having to do this on principal, but it works, so there's that! :) Thanks for sharing this pearl, Geoff! – kayleeFrye_onDeck Mar 20 '15 at 18:27
  • Worked, but instead of .pdb file I took .dll one - this is what @JohnySkovdal said in above comment! – Slawomir Brys Jul 07 '15 at 11:00
  • Let's put an end this annoying madness, please vote [here](https://developercommunity.visualstudio.com/content/problem/62419/building-multi-platform-solutions-has-become-a-nig.html) – Shimmy Weitzhandler May 29 '17 at 01:34
  • 1
    Latest (2018-03-11) Visual Studio 2017 v15.6.1: still an issue. Debugging, exception, assemblies in the target directory locked. The above solution with *.pdb changed to *.dll still applies. – Michiel de Wolde Mar 11 '18 at 09:30
  • 1
    To save some a little time... To add this, right click on your project name, select "Properties" Expand "Build" Select "Events" and enter this into the "Pre-build event" textbox. – Danimal111 Apr 19 '23 at 12:35
103

It's because you have closed your application, but it's still running in background.

Temporary solution:

  • Go to Task Manager (Ctrl + Shift + Esc).
  • Go to Processes tab and find "YourProjectName.exe".
  • Check "Show processes from all users" if you can't find your process.
  • End Process it.

Permanent solution: you have to close your application through coding. Here is the code...

System.Windows.Forms.Application.Exit();

You have to put this code in to the form's closing event in all form. Example:

private void frm_menu_FormClosing(object sender, FormClosingEventArgs e)
{
    System.Windows.Forms.Application.Exit();
}
Espy
  • 3
  • 4
Rushi Daxini
  • 1,570
  • 1
  • 10
  • 14
  • 2
    This was exactly it. Visual Studio had crashed and IIS Express was still running (in my case). All I had to do was open the task bar and right-click the IIS Express icon and exit. Thank you. – the-nick-wilson Jul 25 '17 at 03:16
  • This worked for me; I couldn't delete the obj and bin folders as another process was using them. Thankfully Windows 10 actually said what the name of it was; once it was closed in Task Manager the problems went away – Novastorm Mar 23 '18 at 14:47
  • On my side it was on the User tab. Also, I found it using the [Process Explorer](https://learn.microsoft.com/en-us/sysinternals/downloads/process-explorer) – Eyup Yusein Nov 11 '20 at 05:42
  • Logged off server... logged back on... Issue GONE! Thanks for this permanent fix also... My trouble was killing the process over and over while debugging due to issues... – Danimal111 May 26 '22 at 23:08
  • Worked for me. I ended the background process and rebuild. – Brijesh Ray May 15 '23 at 04:32
25

the .vhost.exe is a debugger process, so it appears that the process being debugged hasn't closed properly. Chances are you have a bug that's keeping it alive and are not stopping the debug process correctly - there are options to detach from the process when you click 'stop debugging' instead of actually killing the debugger so maybe you have that set.

But that's the problem - the file you're trying to copy over is locked (ie still being used) by the OS so its preventing the copy. Ensure that file is free and you'll be able to copy.

gbjbaanb
  • 51,617
  • 12
  • 104
  • 148
  • I've added my debugger options to the questions. I'm pretty sure it should be killing the process but maybe I don't understand some options. – bradgonesurfing Aug 07 '13 at 12:17
  • In `Visual Studio 2019`, I am getting a similar message, although it now mentions the process in some of the output (not all). It was testhost.x86.exe that I had to kill off via `Task Manager`. After that it did seem to stop detecting one of the test processes. – Andez Feb 14 '20 at 19:00
25

I have solved it by killing IISExpress in task manager

pat capozzi
  • 1,412
  • 1
  • 20
  • 16
22

The problem is that the debugger/builder creates the executable or library that is identified as a threat by the Anti-virus and therefore deleted right before it could be executed.

Preferably you should tweak your Anti-Virus software to not analyse your project folder.


Some ways to do this, ranked from best to worse, are:

  1. Excluding your project folder from the Anti-Virus
  2. Excluding pdb files (Not a 100% guaranteed fix)
  3. Turning off Real-Time protection (Not Recommended)
Woody1193
  • 7,252
  • 5
  • 40
  • 90
Pitrs
  • 221
  • 2
  • 2
  • Good catch. I forever hate Avast. – stackunderflow Aug 14 '14 at 23:49
  • Avast was the problem for me too. Disabling the File System Shield was the answer. I tried adding my Visual Studio\Projects folder to the Exclusions but that didn't work. – KeithB Dec 09 '14 at 13:03
  • 1
    I have the same problem with Symantec Endpoint protection. Someone in the IT department has ratcheted up the security level pretty high :-) Thanks Pitrs. – ssimm Aug 24 '16 at 14:56
  • I will add, that you can create exception for the obj\Debug directory for convinient use, instead of disabling the AV or one of it's protective tools. – A. Kali Feb 15 '17 at 11:07
  • Thanks! I found that it was an MalwareBytes blocking my .exe file. – NL3294 Mar 15 '17 at 23:22
16

I was able to fix this issue (VS 2010) through supplying following pre build action;

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

if exist "$(TargetPath)" if not exist "$(TargetPath).locked" move "$(TargetPath)" "$(TargetPath).locked"
S.N
  • 4,910
  • 5
  • 31
  • 51
  • 1
    @luckyluke, In your project properties, there is section where you can add pre-Build script. Copy and past the above script in that designated area and rebuild the project / run your application – S.N Sep 21 '17 at 11:26
13

Quote:

A workaround is to put this in the Pre-build event command line property of the >project (In the build Events tab):

Code Snippet

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

if exist "$(TargetPath)" if not exist "$(TargetPath).locked" move "$(TargetPath)" "$(TargetPath).locked"
usefulBee
  • 9,250
  • 10
  • 51
  • 89
Zheng Qiang
  • 178
  • 1
  • 5
9

Killing the process w3wp.exe (IIS) will often solve this.
Generally, you can know the process that has the lock on the file by navigating to the bin folder and trying to delete it. The error message that will pop up, in case another process is using it, will contain the name of the process that needs to be killed.

Using Blazor and Fluent UI Web Components I got the errors below on publish:

https://learn.microsoft.com/en-us/fluent-ui/web-components/integrations/blazor

C:\Program Files\dotnet\sdk\6.0.402\Sdks\Microsoft.NET.Sdk.Razor\targets\Microsoft.NET.Sdk.Razor.StaticWebAssets.targets(615,5): Warning MSB3026: Could not copy "C:\Users\oscar.nuget\packages\microsoft.fast.components.fluentui\1.5.3\staticwebassets\icons\TextDirectionRotate270Right\en\text_direction_rotate_270_right_24_regular.svg" to "C:\Users\oscar\source\repos\MyVeryLongProjectName12345678\MyVeryLongProjectName12345678\Server\obj\Release\net6.0\PubTmp\Out\wwwroot_content\Microsoft.Fast.Components.FluentUI\icons\TextDirectionRotate270Right\en\text_direction_rotate_270_right_24_regular.svg". Beginning retry 10 in 1000ms. Could not find a part of the path 'C:\Users\oscar\source\repos\MyVeryLongProjectName12345678\MyVeryLongProjectName12345678\Server\obj\Release\net6.0\PubTmp\Out\wwwroot_content\Microsoft.Fast.Components.FluentUI\icons\TextDirectionRotate270Right\en\text_direction_rotate_270_right_24_regular.svg'. C:\Program Files\dotnet\sdk\6.0.402\Sdks\Microsoft.NET.Sdk.Razor\targets\Microsoft.NET.Sdk.Razor.StaticWebAssets.targets(615,5): Warning MSB3026: Could not copy "C:\Users\oscar.nuget\packages\microsoft.fast.components.fluentui\1.5.3\staticwebassets\icons\TextDirectionRotate270Right\en\text_direction_rotate_270_right_20_regular.svg" to "C:\Users\oscar\source\repos\MyVeryLongProjectName12345678\MyVeryLongProjectName12345678\Server\obj\Release\net6.0\PubTmp\Out\wwwroot_content\Microsoft.Fast.Components.FluentUI\icons\TextDirectionRotate270Right\en\text_direction_rotate_270_right_20_regular.svg". Beginning retry 10 in 1000ms. Could not find a part of the path 'C:\Users\oscar\source\repos\MyVeryLongProjectName12345678\MyVeryLongProjectName12345678\Server\obj\Release\net6.0\PubTmp\Out\wwwroot_content\Microsoft.Fast.Components.FluentUI\icons\TextDirectionRotate270Right\en\text_direction_rotate_270_right_20_regular.svg'. C:\Program Files\dotnet\sdk\6.0.402\Sdks\Microsoft.NET.Sdk.Razor\targets\Microsoft.NET.Sdk.Razor.StaticWebAssets.targets(615,5): Error MSB3027: Could not copy "C:\Users\oscar.nuget\packages\microsoft.fast.components.fluentui\1.5.3\staticwebassets\icons\TextDirectionHorizontalRight\ko\text_direction_horizontal_right_24_regular.svg" to "C:\Users\oscar\source\repos\MyVeryLongProjectName12345678\MyVeryLongProjectName12345678\Server\obj\Release\net6.0\PubTmp\Out\wwwroot_content\Microsoft.Fast.Components.FluentUI\icons\TextDirectionHorizontalRight\ko\text_direction_horizontal_right_24_regular.svg". Exceeded retry count of 10. Failed.

Looking at

C:\Users\oscar\source\repos\MyVeryLongProjectName12345678\MyVeryLongProjectName12345678\Server\obj\Release\net6.0\PubTmp\Out\wwwroot\_content\Microsoft.Fast.Components.FluentUI\icons\TextDirectionHorizontalRight\ko\text_direction_horizontal_right_24_regular.svg

It is 261 characters long.

I then tried to Enable Long Paths and reboot my computer.

https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=registry

This did not work and I got the same error. I then moved my project to C:\MyVeryLongProjectName12345678\ instead of C:\Users\oscar\source\repos\MyVeryLongProjectName12345678\. After doing this everything worked out.

Ogglas
  • 62,132
  • 37
  • 328
  • 418
  • Curiously, I ran into this even though my path was only 161 characters. The setting in the registry definitely had the same default value. So it's very strange that enabling Long Path names actually worked to resolve this. I think there must have been a bit more going on. Also, I didn't have to reboot my computer after changing the setting. That was unexpected. – ouflak Jan 18 '23 at 13:13
  • +1 Only this solution worked for me. I had taken checkout of a new branch on my local. And one of the .sql embedded resource was using long file name. Trimming the file name fixed the issue. – nraina Jan 31 '23 at 10:50
9

Exception

In some cases in Visual Studio when you (Build || Rebuild) on top of running IISExpress you faced with this Exception:

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

Solution

  1. Right click on web project that needs to build.
  2. Click on properties.
  3. Select Build Events Tab on the left side.
  4. In Pre-build events command line paste these 2 line:
tasklist /fi "imagename eq iisexpress.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "iisexpress.exe"

You are good 2 GO!

Xaimaran
  • 403
  • 4
  • 17
9

Follow the below steps

  1. Open Task Manager ( Ctrl + Alt + Delete )
  2. Under Performance tab select select <ProjectNameOfYours.exe>.
  3. Click on End Process.
  4. Now Build solution.

Above steps resolved error permanently :)

Akshay Bagi
  • 179
  • 1
  • 8
8

My 10 cents contribution.

I still have this problem occasionally on VS 2015 Update 2.

I found that switching compilation target solves the problem.

Try this: if you are in DEBUG switch to RELEASE and build, then back to DEBUG. The problem is gone.

Stefano

Stefano.net
  • 1,078
  • 1
  • 11
  • 25
  • Yeah! That's it. This is a simple solution to this annoying problem! Totally worked for me. Easy and quick! Thanks alot. – Meister Schnitzel Jan 24 '17 at 06:35
  • 1
    It works for me! Hint: With deactivated Debug>>Options>>Debugging>>General>>"Use Managed Compatibility Mode" the workaround is not required! – leon22 Aug 06 '18 at 08:47
  • The problem still exists in VS2022! Valuable 10cts from Stefano! Thanks! Much quicker for a larger project than closing and re-opening VS, which works also. – josh May 14 '22 at 11:25
7

It seems that by change the assembly name of a project fixes the problem.

So instead of this

enter image description here

I change it to this

enter image description here

Notice that I just changed it from Increment and Recall to Increment_Recall, I just removed the spaces. It is now working fine to me.

Cary Bondoc
  • 2,923
  • 4
  • 37
  • 60
6

I think I solved it removing the check mark to Break all processes when one process breaks in Debug options (op's first screenshot->second option).
It's been building/running well for a while since I unchecked it.
I'm using MySql NET Connector and DevExpress controls in my project. May be one of them was not disposing connections, bindings, etc. well because of this flag beeing activated.

EDITED: definitely it works! No more 'Unable to copy file' and no more Form designer errors.

Ivan Ferrer Villa
  • 2,129
  • 1
  • 26
  • 23
  • 1
    None of the other solutions worked for me. This is the only one. I´m using Visual Studio 2017 13.2 – xleon May 16 '17 at 16:26
  • This works always. I use VS2013 Community Edition. Here is my Solution with 17 projects: http://qurancode.com – Ali Adams Nov 29 '20 at 06:48
5

If none of the answers works, try this simple check. Find for any MSbuild.exe running and holding your project EXE. Kill MSBuild.exe and you should be good to go.

Gentleman
  • 130
  • 1
  • 8
4

I faced the same problem on VS 2012 Version 11.0.60610.01 Update 3 on Windows 8

There were no designer windows open and the project was a simple console application.

The removal of the vshost process accessing the file does not work most of the time since the process isn't accessing the file.

The simplest workaround that works and takes the least amount of time is to remove the project from the solution, build another project in the solution and then add the original back.

It's an irritant and waste of time but it's the least expensive of all the other options that I know of.

Hope this helps...

Ashwin J
  • 41
  • 1
  • All you have to do is Rebuild All and everything's fine for another 10 tries. Not much of an inconvenience. – Scott Shaw-Smith Jun 24 '15 at 15:36
  • @Scott Shaw-Smith Doesn't work for me. And based on some of the other comments I've seen, it doesn't work for others either. In my case uninstalling Avast fixed it. – user316117 Aug 05 '15 at 15:02
4

Add in pre-build event of your master project taskkill /f /fi "pid gt 0" /im "YourProcess.vshost.exe"

sofsntp
  • 1,964
  • 23
  • 34
3

I cannot give a solution to prevent this from happening but you can at least RENAME the locked file (windows explorer, or classic command window) and then compile/build. No need to reboot or restart VS201x. With some experience you can add a pre-build script to delete old files or rename then out-of-the-way in case there's a lock.

hopperpl
  • 298
  • 3
  • 8
3

See this other answer. Basically, you could have MSBuild.exe processes running in the background consuming resource files. If you have any pre or post build tasks that cause an MSBuild to be kicked off via command line, try adding the "/nr:false" flag to this command. But again, see the previous answer for more specific details.

Community
  • 1
  • 1
  • Snap, i have the same problem in VS2015 update 2 - MSBuild,exe process needs to be killed in TaskManager before I can re-build. – Nick Wright Jun 02 '16 at 09:09
  • The article link in Josh's answer above suggests using a system environment variable to disable node reuse within Visual Studio and the MSBuild process (MSBUILDDISABLENODEREUSE=1) - this worked for me. – Nick Wright Jun 02 '16 at 09:30
3
  1. Open project properties [ menu > project > properties ]
  2. Choose "debug" tab
  3. Uncheck "Enable the visual studio hosting process"
  4. Start debugging [F5]
  5. You will receive security warning , just "ok". Lets application running
  6. Stop debugging.
  7. Check option "Enable the visual studio hosting process" , under debug tab,
  8. Now , try to start debugging , you will not see error again

[Work for me]

Novpiar Effendi
  • 307
  • 3
  • 4
2

I finally how fix it. Why we can't continue debug after the first debug because the first debug exe still running. So that, after first debug, you need to go to Task Manager -> Process Tab -> [your project name exe] end the exe process.

it works for me :)

chevhfghfghfgh
  • 127
  • 1
  • 6
  • Wow, Thanks man, exactly my problem. As it asks user password for me while running exe, first time it didn't fire. When i try to delete that app in process list and then debug again, it worked flawlessly. – Chandraprakash Mar 03 '20 at 15:44
2

In my case it was Resharper Unit Tests runner (plus NUnit tests, never had such problem with MsTests). After killing the process, was able to rebuild process, without restarting OS or VS2013.

Other test runners, like xUnit can cause the same issue.

What helps then is to check if you can add a Dispose pattern, for example if you're adding a DbFixture and the database contacts isn't disposed properly. That will cause the assembly files being locked even if the tests completed.

Note that you can just add IDisposable interface to your DbFixture and let IntelliSense add the Dispose pattern. Then, dispose the related contained propertys and explicitly assign them to null.

That will help to end the tests in a clean way and unlock related locked files as soon as the tests ended.

Example (DBFixture is used by xUnit tests):

public class DbFixture: IDisposable
{
    private bool disposedValue;
    public ServiceProvider ServiceProvider { get; private set; }
    
    public DbFixture()
    {
        // initializes ServiceProvider
    }
    
    
    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // dispose managed state (managed objects)
                ServiceProvider.Dispose();
                ServiceProvider = null;
            }

            // TODO: free unmanaged resources (unmanaged objects) and override finalizer
            // TODO: set large fields to null
            disposedValue = true;
        }
    }

    // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
    // ~DbFixture()
    // {
    //     // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
    //     Dispose(disposing: false);
    // }

    public void Dispose()
    {
        // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }
}

The same pattern you need for the test class itself - it needs its own Dispose method (as shown for the DbFixture class above):

   public SQL_Tests(ITestOutputHelper output)
    {
        this.Output = output;
        var fixture = new DbFixture(); // NOTE: MS Dependency injection framework didn't initialize when the fixture was a constructor param, hence it is here
        _serviceProvider = fixture.ServiceProvider;
    } // method

So it needs to dispose its local property _serviceProvider in its own Dispose method, because the test class constructor SQL_Tests instanciated it.

Matt
  • 25,467
  • 18
  • 120
  • 187
Uriil
  • 11,948
  • 11
  • 47
  • 68
  • Yep, look for `JetBrains.Resharper.TaskRunner.*` – Dunc Jun 21 '16 at 14:32
  • 1
    You had the right idea, I added something from my experience with xUnit because the issue burned me lot of my time and wasn't easy to fix... hope it is helpful. – Matt Feb 02 '21 at 09:30
2

I didn't realize I still had my debugger attached and was trying to build in the same Visual Studio instance. Once I stopped the debugger I was able to build.

Valamas
  • 24,169
  • 25
  • 107
  • 177
2

@Geoff's (https://stackoverflow.com/a/25251766/3739540) answer is good, but it throws error code 1 on recompile.

Here is what worked for me (2>nul 1>nul on the end + exit 0):

(if exist "$(TargetDir)*old.pdb" del "$(TargetDir)*old.pdb") & (if exist "$(TargetDir)*.pdb" ren "$(TargetDir)*.pdb" *.old.pdb) 2>nul 1>nul
(if exist "$(TargetDir)*old.dll" del "$(TargetDir)*old.dll") & (if exist "$(TargetDir)*.dll" ren "$(TargetDir)*.dll" *.old.dll) 2>nul 1>nul
exit 0
Community
  • 1
  • 1
Michael Ribbons
  • 1,753
  • 1
  • 16
  • 26
2

I have noticed some answers that solved my problem, BUT, just in case anyone is having the same problem I was.

IF YOU ARE RUNNING A CONSOLE APP: BEFORE YOU DO ANYTHING ELSE.

Make sure you have closed out any console windows that may have been opened from a previous build. For instance I was just testing some code in a console application, I didn't realize that the console window from one of the previous times I ran my program was open. During that session I was debugging, the window got pushed to the back and I couldn't see it. Just saying, this could be your problem, so check to make sure that is not the problem.

Eric Bishard
  • 5,201
  • 7
  • 51
  • 75
2

If you are debugging T4 templates, then this happens all the time. My solution (before MS fixes this) would be just to kill this process:

Task Manager --> User --> T4VSHostProcess.exe

This process only comes up when you debug a T4 template, not when you run one.

Pompair
  • 7,083
  • 11
  • 60
  • 69
2

Here is a script to definitely get rid of this issue:

REM   This script is invoked before compiling an assembly, and if the target file exist, it moves it to a temporary location
REM   The file-move works even if the existing assembly file is currently locked-by/in-use-in any process.
REM   This way we can be sure that the compilation won't end up claiming the assembly cannot be erased!

echo PreBuildEvents 
echo  $(TargetPath) is %1
echo  $(TargetFileName) is %2 
echo  $(TargetDir) is %3   
echo  $(TargetName) is %4

set dir=C:\temp\LockedAssemblies

if not exist %dir% (mkdir %dir%)

REM   delete all assemblies moved not really locked by a process
del "%dir%\*" /q

REM   assembly file (.exe / .dll) - .pdb file and eventually .xml file (documentation) are concerned
REM   use %random% to let coexists several process that hold several versions of locked assemblies
if exist "%1"  move "%1" "%dir%\%2.locked.%random%"
if exist "%3%4.pdb" move "%3%4.pdb" "%dir%\%4.pdb.locked%random%"
if exist "%3%4.xml.locked" del "%dir%\%4.xml.locked%random%"

REM Code with Macros
REM   if exist "$(TargetPath)"  move "$(TargetPath)" "C:\temp\LockedAssemblies\$(TargetFileName).locked.%random%"
REM   if exist "$(TargetDir)$(TargetName).pdb" move "C:\temp\LockedAssemblies\$(TargetName).pdb" "$(TargetDir)$(TargetName).pdb.locked%random%"
REM   if exist "$(TargetDir)$(TargetName).xml.locked" del "C:\temp\LockedAssemblies\$(TargetName).xml.locked%random%"

REM PreBuildEvent code
REM   $(SolutionDir)\BuildProcess\PreBuildEvents.bat  "$(TargetPath)"  "$(TargetFileName)"  "$(TargetDir)"  "$(TargetName)"

REM References:
REM   http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx
REM   http://stackoverflow.com/a/2738456/27194
REM   http://stackoverflow.com/a/35800302/27194

The script needs to be invoked from each VS project pre build event.

$(SolutionDir)\BuildProcess\PreBuildEvents.bat  "$(TargetPath)"  "$(TargetFileName)"  "$(TargetDir)"  "$(TargetName)"

enter image description here

Patrick from NDepend team
  • 13,237
  • 6
  • 61
  • 92
2

I found a complete solution!

Most answers tell you to kill the process, however with process hacker, I couldn't find any.

I found a relatively simple solution.

  1. Select your primary form in the Form Designer.
  2. Click to your events tab on the properties menu.
  3. Doubleclick the event FormClosing. This automatically generates the event system and function:

private void [your form name here]_FormClosing(object sender, FormClosingEventArgs e)

  1. Inside this function, add Application.Exit

Like so:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    Application.Exit();
}

helpful image

enter image description here

enter image description here

I hope this helps! This problem really sucked!

Fix 2

Turn on a service called 'Application Experience.'

Kelvin Wang
  • 627
  • 5
  • 21
  • 1
    This existed for u because your code was not properly closing the form. This is not a complete solution. There is a mistake in your code keeping the windows forms application and you added code to kill your app – John Demetriou Mar 09 '18 at 12:01
  • Oh, good reminder. The problem came back following a restart of Visual Studio. The thing that fixed it finally turned out to be enabling a service called 'Application Experience.' – Kelvin Wang Mar 09 '18 at 14:07
2

You can kill the application by script.

If your application is named myapp.exe, run the next script in the terminal:

taskkill /IM myapp.exe /F

the parameters are:

/IM   application name (imagename)

 /F                     Specifies to forcefully terminate the process(es).
M.Hassan
  • 10,282
  • 5
  • 65
  • 84
1

This question was the first result when looking for the following error:

Could not copy the file "..." because it was not found.

when building in Visual Studio 2013 (Update 3).

Solution: Uninstalling the "Productivity Power Tools" in Visual Studio 2013.

https://connect.microsoft.com/VisualStudio/feedback/details/533411

carraua
  • 1,398
  • 17
  • 36
  • Getting this error many times on build for inherited project from TFS. Thought this was it! Searched for this in installed programs, and add-ins. Cannot find this power tools application. Where would this hide? – Taersious Jun 17 '19 at 15:58
1

Killing the vstest.executionengine.exe process(es) resolves this issue 90% of the time for me. If that doesn't work, then also killing QTAgent32.exe and then deleting the /bin and /obj folders for the project in question works.

This is the most irritating part of my work day. :)

dgundersen
  • 447
  • 3
  • 16
1

For me it was the Avast antivirus that wont let visual studio to write/read/execute file. So I had to add Visual studio 2010/2012 folder to antivirus exclusion list. And right after that baam... it works.

Alex
  • 1,052
  • 1
  • 11
  • 22
1

Make sure u close all instances wcfSvcHost and try again. It worked for me!

Ocelot
  • 1,733
  • 4
  • 29
  • 53
1

In my case (Windows 10, Visual Studio 2015) :

Task Manager -> Users -> EndTask=>vshost.exe

(it restarts immediately and you can build again)

Adi
  • 475
  • 5
  • 15
1

Add this to the pre-built:

(if exist "$(TargetDir)*old.exe" del "$(TargetDir)*old.exe") & (if exist "$(TargetDir)*.exe" ren "$(TargetDir)*.exe" *.old.exe)
tmighty
  • 10,734
  • 21
  • 104
  • 218
1

In my case the files VS coulnd't copy were those of the .Task project, so the problem was that I had a few scheduled tasks running locally. Once I stopped and disabled them, the copy problem disappeared.

electrodrel
  • 365
  • 2
  • 8
1

In my case it was a permission problem. I had to run Visual Studio as administrator.

Tonatio
  • 4,026
  • 35
  • 24
1

Sometimes it cannot clear the DEBUG folder. What I did and worked was renaming the file that could not be deleted. So, erase all the folder and the file that cannot be deleted, rename to, for example, "_old".

Allan Zeidler
  • 317
  • 2
  • 7
1

I am working on a micro service projects solution where I need to run two projects at the same time, the conflict occurs when the lunchsettings.json applicationurl: {portNo} part for the two running projects are the same port

lunchsettings.json for first project

...
"Project#1": {
  ...
  "applicationUrl": "http://localhost:5001",
  ...
}

lunchsettings.json for second project

...
"Project#2": {
  ...
  "applicationUrl": "http://localhost:5001",
  ...
}

To fix it

lunchsettings.json for first project

...
"Project#1": {
  ...
  "applicationUrl": "http://localhost:5001",
  ...
}

lunchsettings.json for secondproject

...
"Project#2": {
  ...
  "applicationUrl": "http://localhost:5002",
  ...
}
iDeveloper
  • 1,699
  • 22
  • 47
Dicekey
  • 405
  • 4
  • 12
1

@Gerard's answer was correct.

When clean+build has not resolved this problem for me, I have had success by doing the following:

Closing Visual Studio
Deleting the bin and obj folders, and
Reopening Visual Studio.

But I needed to do some extra work in console:

> Add-Migration Initial
> Update-Database

Then I started to debug and it worked.

iDeveloper
  • 1,699
  • 22
  • 47
1

I have add the same problem various times and none of the answers from this treat could help or if they did it was by using a nasty work around.
What I figured is that there is always a good reason for this problem to occur (And is not a Microsoft bug! - Well, VS could get better at flagging it though :-)).

The main reason may simply be that your project dependencies are messed up!
As a simple example ():

  • You have multiple projects within a same solution
  • You clean + build all and assume everything went well as you see no error
  • You start running one of the project - All good so far!
  • Then start running a second one, but this one has dependencies also used by the previous project and tries to rebuild them
  • It then hangs for a while
  • It fails to build as the first project is already running and does not allow you to override ongoing processes

Now you can think of all the possible scenarios that could trigger an error of the sort:

Error Could not copy "obj\Debug\ProjectX.exe" to "..\bin\Debug\ProjectX.exe". Exceeded retry count of 10. Failed. The file is locked by: "ProjectX (17132)" ProjectX

Fixing this issue is usually a tedious process as you will have to perfectly understand all the dependencies in your system

progLearner
  • 123
  • 10
1

You must kill the process after closing. I fixed it with;

Process.GetCurrentProcess().Kill();

Add this code to closing event or method whats you use for closing.

OAslan
  • 102
  • 4
1

If you're running into this issue using Visual Studio Code (vsCode) and/or you're sticking to terminal commands, the clean command will delete the build files and typically fix the issue described:

dotnet clean

Then, you can return to running:

dotnet build

or

dotnet run
WEFX
  • 8,298
  • 8
  • 66
  • 102
0

I get this every time I deploy if I edit a Xaml page on WP8 using VS2012.

I need to either not open a Xaml page or use process explorer to kill the process XDesProc.exe.

If you are getting this error then I recommend using process explorer to see what is happening (even if it's a different problem). Just find the process "WeinGartner.WeinCad.exe" and it should show the process and handle accessing the file (well at least when the killing the vhost file doesn't fix the issue).

Luke
  • 2,851
  • 1
  • 19
  • 17
0

Check the task manager for any process running the .exe

0

Another kludge, ugh, but it's easy and works for me in VS 2013. Click on the project. In the properties panel should be an entry named Project File with a value

(your project name).vbproj

Change the project name - such as adding an -01 to the end. The original .zip file that was locked is still there, but no longer referenced ... so your work can continue. Next time the computer is rebooted, that lock disappears and you can delete the errant file.

den232
  • 682
  • 6
  • 14
0

Delete any .cache files under your Debug or Release folders inside the Bin folder.

alwaysVBNET
  • 3,150
  • 8
  • 32
  • 65
0

I encountered this problem in VS 2015. The reason for my environment was use of StyleCop project setting for StyleCopAdditionalAddinPaths Include="..." to specify additional StyleCop Addin path. The workaround I used was to remove this project setting from .csproj file, and instead, copy the StyleCop AddIn manually where the StyleCop.CSharp.Rules.dll was present. Not an elegant solution, but I found that the solution never locked the dlls after doing this.

nkanani
  • 548
  • 1
  • 6
  • 7
0

I ran into this as well. It turns out that I had been testing with a service which I had built myself and which was running out the of the ..\bin\release directory of one of the projects in my solution. I had got the service running, but I forget to stop/uninstall it before returning to testing. As a result, it was holding on to one of the dlls that I reference and which needed to be moved (automatically as a dependency) from one project's bin/release subfolders to another. Stopping the service solved the problem.

Rob
  • 3,488
  • 3
  • 32
  • 27
0

The fastest way is changing the Build configuration type and return to previous configuration again.

Ehsan Mohammadi
  • 415
  • 4
  • 15
0

This happened to me while using the IL Support plugin.

When you do not have any IL file in your project (because you deleted the last one for example), build fails as described in the question.

Removing support of IL resolved the issue

Regis Portalez
  • 4,675
  • 1
  • 29
  • 41
0

Reset IIS, stop services which are using your DLL (maybe console app or windows services hosted app or IIS) and then try.

It worked for me.

Rohit Patel
  • 459
  • 2
  • 14
0

I experienced the error-messages when attempting to build the primary WinForms (XAF) project. I could only execute the application one time then needed to shutdown the VS2015 IDE and restart before a rebuild could be performed. After some digging in the project's property pages - in the "debug" property page, a check box was selected - Enable the Visual Studio Hosting Process. I unchecked and restarted the IDE, the application is now building without - "unable to copy the {project}.exe" messages.

What is the purpose of the Visual Studio Hosting Process?

Community
  • 1
  • 1
Tim P
  • 69
  • 1
  • 9
0

I periodically have this problem as well in Visual Studio 2010. Closing Visual Studio, deleting the bin and obj directories, and re-launching will fix it for one build. Then the problem returns. I have tried every other answer on this thread and none worked for me. The only thing that resolves this permanently for me is to go to the project settings and turn off "Enable the Visual Studio hosting process", build, turn it back on, and build again.

Drew Chapin
  • 7,779
  • 5
  • 58
  • 84
0

In my case the Visual Studio 2105 Remote Debugger was the problem. When I killed this task in Task Manager I was able to successfully rebuild my application in Visual Studio.

David Cader
  • 111
  • 3
0

I had the same problem and I tried so many different ways mentioned here but none of them worked for me, the only solution that worked for me:

  1. Removing the READ ONLY Property from DEBUG folder of my solution and

  2. Adding this to Build events: if exist "$(TargetPath).locked" del "$(TargetPath).locked" if not exist "$(TargetPath).locked" if exist "$(TargetPath)" move "$(TargetPath)" "$(TargetPath).locked"

0

Using DNN. I solved the problem by editing the MSBuild.Community.Tasks.Targets file and changing the bin path:

<MSBuildDnnBinPath Condition="'$(MSBuildDnnBinPath)' == ''">$(MSBuildProjectDirectory)\bin</MSBuildDnnBinPath>
live-love
  • 48,840
  • 22
  • 240
  • 204
0

I was going crazy trying to find why System process held an open handle on the EXE I was working with for another minute after it was terminated, and I was getting the same error as the OP.

The reason was that the previous developers did not wrap IDisposable objects in using(){}. Once the IDisposable objects correctly destroyed themselves, the error occurred no more and I was able to rebuild immediately.

ajeh
  • 2,652
  • 2
  • 34
  • 65
0

I realize this is just adding to the already huge amount of answers for this question, but thought it deserved mentioning that, although not perfect, a combination of the answers given by: @Stefano, @MichaelRibbons, and @IvanFerrerVilla has provided a decent bit of success, when neither of them on their own was very successful.

drlff
  • 256
  • 3
  • 12
0

Spent a few hours trying to sort this out, then found out I was working on a service - remember to stop any services as part of your solution!

Joe
  • 6,773
  • 2
  • 47
  • 81
0

I managed to get around the issue by running the Visual Studio as administrator.

Shahin
  • 12,543
  • 39
  • 127
  • 205
0

In my case, I was having trouble publishing to a folder that it was having trouble accessing. You can rule this out by trying to publish to a folder in your c drive which you should not have an issue accessing.

Josh
  • 189
  • 8
0

Use Ms Process Explorer to find out that you need to turn on "Application Experience" in Windows 7

In my case, none of all the other suggestions worked (Windows 7, VS2019)

After compiling, the generated .EXE file was reproducably locked for about one minute. Another strange observation: When deleting the .EXE file, it disappeared in the File Explorer like usual, but then re-appeared when refreshing (F5).

You can use MS Process Explorer to find out if any process holds a handle on your generated .EXE file. To do so, view the "lower pane" of the Process Explorer, select viewing handles instead of DLLs, and use "Find" to search for your .EXE file.

This showed me that is was the Windows 7 "System" process that got a handle on the .EXE.

Some research then revealed that i had to turn on the Windows "Application Experience" service ("automatic start") to permanently get rid of this strange behaviour.


Here is some more info: Under which circumstances does the System process (PID 4) retain an open file handle?

0

This issue commonly occurs when running tests. If this is your case just go to Task Manager and kill testHost

John Nyingi
  • 951
  • 1
  • 16
  • 36
0

Press Cntrl+alt+Delete then go to resource monitor and select your exe name under CPU tab, right click and kill that process. enter image description here

sorma Gupta
  • 107
  • 1
  • 4
0

The first message error solution:

In my case, the problem was with the path length.

The solution is to reduce/change the problem file path. If the problem is with a file inside your project, you should reduce/change the repository path from e.g.

C:\Users\userTest\folder1\folder2\folder3\...\folderX\myProject\...\file.exe

to e.g.

C:\Users\userTest\folder1\myProject\...\file.exe

In others words by default the path length can't be upper than 260 characters.

Original thread answer (https://stackoverflow.com/a/73686473/12678101)

pear95
  • 66
  • 1
  • 6
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/32709519) – Z0OM Sep 18 '22 at 08:31
  • Fixed. You are absolutely right, I didn't think that the linked page could change. Thanks for the hint. – pear95 Sep 18 '22 at 10:09
0

In my case I had an instance of Azure Data Studio that was accessing the .dll as part of a deployment operation.

Always check that there is nothing using the file that you are trying to replace.

Divan
  • 309
  • 2
  • 3
  • 14
-1

go to Tools>>Options>>DataBase Tools>>General Check Sqript/Query Execution

-3

Use

Debug.Flush();
Debug.Close();

in case exception occurs, in catch or finally block.

Edit: I personally faced this issue and I do a trick usually and it works fine. I change the type of build from 'debug' to 'release' (and 'release' to 'debug' if there is already).

Lali
  • 2,816
  • 4
  • 30
  • 47
  • Had the error, littered my code with Flush/Close in Finally blocks and Dispose methods. No effect at all. If anyone confirms that this works I'll remove my -1 on this answer. – TonyG Aug 08 '14 at 17:13