Visual studio не удалось скопировать obj debug
Update: A sample project reproducing this bug can be found here at Microsoft Connect. I have also tested and verified that the solution given in the accepted answer below works on that sample project. If this solution doesn't work for you, you are probably having a different issue (which belongs in a separate question).
This is a question asked before, both here on Stack Overflow and other places, but none of the suggestions I've found this far have helped me, so I just have to try asking a new question.
Problem: All was fine for a while. Then, all out of the blue, Visual Studio failed to build when I was about to launch the application. I got the warning "Unable to delete file '. bin\Debug\[ProjectName].exe'. Access to the path '. bin\Debug\[ProjectName].exe' is denied." and the error "Unable to copy file 'obj\x86\Debug\[ProjectName].exe' to 'bin\Debug\[ProjectName].exe'. The process cannot access the file 'bin\Debug\[ProjectName].exe' because it is being used by another process." (I get both the warning and the error when running Rebuild, but only the error when running Build - don't think that is relevant?)
I understand perfectly fine what the warning and error message says: Visual Studio is obviously trying to overwrite the exe-file while it at the same time has a lock on it for some reason. However, this doesn't help me find a solution to the problem. The only thing I've found working is to shut down Visual Studio and start it again. Building and launching then work, until I make a change in some of the forms, then I have the same problem again and have to restart. Quite frustrating!
As I mentioned above, this seems to be a known problem, so there are lots of suggested solutions. I'll just list what I've already tried here, so people know what to skip:
Creating a new clean solution and just copy the files from the old solution.
Adding the following to the following to the project's pre-build event:
Adding the following to the project properties (.csproj file):
However, none of them worked for me, so you can probably see why I'm starting to get a bit frustrated. I don't know where else to look, so I hope somebody has something to give me! Is this a bug in VS, and if so is there a patch? Or has I done something wrong, do I have a circular reference or similar, and if so how could I find out?
Any suggestions are highly appreciated :)
Update: As mentioned in the comment below, I've also checked using Process Explorer that it actually is Visual Studio that is locking the file.
(Unable to copy file "obj\Debug\Project1.exe" to "bin\Debug\Project1.exe". The process cannot access the file 'bin\Debug\Project1.exe' because it is being used by another process.)
So I have to close the process from the task manager. My project is only one form and there is no multi-threading.
What is the solution (without restarting VS or killing the process)?
The Tao Framework wraps a bunch of different stuff, any of which might be causing this problem. Which part of the framework are you using? Also, if you could produce a small sample app which demonstrates this problem and post it, it would help debug it.
37 Answers 37
This should work.
Go to your project properties. Inside Build Events, under Pre-build event command line, add these two lines of code:
Thank you, this works perfect. I had troubles with VS2013 PRO and VS2015 ENT. This fix solved the problem.
@Udpate: Since the time I was first posting this 'answer', I tend to another explanation to the problem. The issue since than happened more and more often outside of Visual Studio also - while trying to copy an .exe file from one folder to another. While in the first place Windows did not allow to copy(!) an .exe file (it was first asking me for administrative rights but refused to copy it afterwards anyway) it still showed up in the explorer. But after a while - without any further action taken, it disappeared magically. Just like the problem in the question always seems to solve itself after a while. So i assume, the problem is more related to a delayed deletion of the project output file and less a buggy VS. I apologize for any unjustified suspicion. :|
This gives the search for a solution a complete different direction, I guess. Did find that link and will update on any progress:
This is a known bug in VS. I discovered it very often - mostly in VS2010 (with/without SP1). Several "solutions" are recommended. Some of them, which kind of helped for me:
- Delete the .suo file in your project dir. Eventually need to create your whole solution from scratch.
- Close any Windows Form Designers may remain open.
- Use a prebuild script, which deletes the target from the output dir.
- Disable the VS hosting process.
None of these really fixes the bug. But it may brings the VS back to a usable state - until a true solution is provided by MS (if ever will).
works (sometimes ) but this is getting on my nerves. Any way to stop this happening at all?
My debugger settings are
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.
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.
65 Answers 65
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.
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.
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'
In Visual Studio Premium 2013 (Update 3), I solved this with a pre-build one-liner:
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.
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.
Glad it helped - I still have my pre-build command set up, and it works well enough that I'd forgotten it was there!
I hate having to do this on principal, but it works, so there's that! :) Thanks for sharing this pearl, Geoff!
It's because you have closed your application, but it's still running in background.
- Go to Task Manager ( Ctrl + Alt + 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.
You have to put this code in to the form's closing event in all form. Example:
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.
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
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.
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.
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.
I have solved it by killing IISExpress in task manager
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.
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.
I have the same problem with Symantec Endpoint protection. Someone in the IT department has ratcheted up the security level pretty high :-) Thanks Pitrs.
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.
I was able to fix this issue (VS 2010) through supplying following pre build action;
@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
A workaround is to put this in the Pre-build event command line property of the >project (In the build Events tab):
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
- Right click on web project that needs to build.
- Click on properties.
- Select Build Events Tab on the left side.
- In Pre-build events command line paste these 2 line:
You are good 2 GO!
Follow the below steps
- Open Task Manager ( Ctrl + Alt + Delete )
- Under Performance tab select select ProjectNameOfYours.exe>.
- Click on End Process.
- Now Build solution.
Above steps resolved error permanently :)
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.
It seems that by change the assembly name of a project fixes the problem.
So instead of this
I change it to this
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.
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.
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.
Yeah! That's it. This is a simple solution to this annoying problem! Totally worked for me. Easy and quick! Thanks alot.
It works for me! Hint: With deactivated Debug>>Options>>Debugging>>General>>"Use Managed Compatibility Mode" the workaround is not required!
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.
All you have to do is Rebuild All and everything's fine for another 10 tries. Not much of an inconvenience.
@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.
Add in pre-build event of your master project taskkill /f /fi "pid gt 0" /im "YourProcess.vshost.exe"
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.
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.
- Open project properties [ menu > project > properties ]
- Choose "debug" tab
- Uncheck "Enable the visual studio hosting process"
- Start debugging [F5]
- You will receive security warning , just "ok". Lets application running
- Stop debugging.
- Check option "Enable the visual studio hosting process" , under debug tab,
- Now , try to start debugging , you will not see error again
Why was this at -2? It has worked for me as well. It makes zero sense but hey, if it works, it works.
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.
Snap, i have the same problem in VS2015 update 2 - MSBuild,exe process needs to be killed in TaskManager before I can re-build.
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.
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 :)
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.
Here is what worked for me (2>nul 1>nul on the end + exit 0):
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.
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.
Here is a script to definitely get rid of this issue:
The script needs to be invoked from each VS project pre build event.
You can kill the application by script.
If your application is named myapp.exe , run the next script in the terminal:
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):
The same pattern you need for the test class itself - it needs its own Dispose method (as shown for the DbFixture class above):
So it needs to dispose its local property _serviceProvider in its own Dispose method, because the test class constructor SQL_Tests instanciated it.
работает (иногда ), но это действует мне на нервы. Есть способ остановить это?
Мои настройки отладчика
в основном, я обнаружил, что эта ситуация произошла, когда процесс отладки был остановлен из-за исключения.
когда clean + build не решил эту проблему для меня, я добился успеха, выполнив следующее:
- Закрытие Visual Studio
- удалить bin и obj папки, и
- Повторное Открытие Visual Студия.
эта "ошибка" существует с Visual Studio 2003.
наконец, я также обнаружил, что часто могу преодолеть эту проблему, просто переименовав исполняемый файл, а затем удалив его.
в Visual Studio Premium 2013 (обновление 3) я решил это с помощью предварительной сборки One-liner:
это изящно удаляет любые старые файлы PDB (если это возможно), а затем переименовывает все, что осталось с . Хороший побочный эффект заключается в том, что если старый PDB все еще заблокирован, он просто добавляет другой .старая часть имени файла, и все они очищаются при следующем перезапуске Visual Studio и выполнении сборки.
например, сеанс сборки/отладки 1 оставляет MyProject.pdb заблокированные.
В следующий раз, когда вы строите:
MyProject.pdb --> MyProject.old.pdb
затем запускается сеанс сборки / отладки 2 и и MyProject.pdb и MyProject.old.pdb все еще заблокированы:
MyProject.old.pdb --> MyProject.old.old.pdb
MyProject.pdb --> MyProject.old.pdb
наконец, перезапуск Visual Studio и выполнение новой сборки избавятся от обоих из них и продолжат процесс как обычно.
Это потому, что вы закрыли приложение, но оно продолжает работать в фоновом режиме.
- перейдите в Диспетчер задач ( Ctrl + Alt + Esc ).
- перейдите на вкладку Процессы и найдите "YourProjectName.исполняемый."
- галочку "Отображать процессы всех пользователей", если вы не можете найти свой процесс.
- завершить процесс.
постоянное решение: вы должны закрыть ваше приложение через кодирование. Вот код.
вы должны поставить этот код в событие закрытия формы в форму. Пример:
the .виртуальный хост.exe-это процесс отладчика, поэтому кажется, что отлаживаемый процесс не закрыт должным образом. Скорее всего, у вас есть ошибка, которая поддерживает его в живых и не останавливает процесс отладки правильно - есть опции для отсоединения от процесса, когда вы нажимаете "остановить отладку" вместо фактического убийства отладчика, поэтому, возможно, у вас есть этот набор.
но это проблема-файл, который вы пытаетесь скопировать, заблокирован (т. е. все еще используется) ОС, поэтому его предотвращение копирования. Убедитесь, что файл свободен, и вы сможете скопировать его.
Я решил это, убив IISExpress в диспетчере задач
вы должны отключить антивирус (особенно, если это Avast) и повторите попытку. Это помогло мне. Проблема в том, что отладчик/построитель создает.exe-файл, который идентифицируется как угроза Avast и поэтому удаляется прямо перед его выполнением VS.
обходной путь должен поместить это в свойство командной строки события Pre-build > project (на вкладке События сборки):
исключение
в некоторых случаях в Visual Studio, когда вы (Build || Rebuild) поверх под управлением IISExpress вы столкнулись с этим исключением:
не удается скопировать файл " obj\Debug\YourProjectName.dll " в bin\YourProjectName.файл DLL." the процесс не может получить доступ к файл 'bin\YourProjectName.библиотеки DLL' потому что он используется другим процесс
решение
- щелкните правой кнопкой мыши на веб-проекте, который нужно построить.
- нажмите на "свойства".
- выберите вкладку события сборки с левой стороны.
- в командной строке событий предварительной сборки вставьте эти 2 строки:
вы хорошо 2 идти!
Я столкнулся с той же проблемой на VS 2012 версии 11.0.60610.01 обновление 3 на Windows 8
не было открытых окон конструктора, и проект был простым консольным приложением.
удаление процесса vshost доступа к файлу не работает большую часть времени, так как процесс не обращается к файлу.
самым простым обходным путем, который работает и занимает наименьшее количество времени, является удаление проекта из решения, создание другого проекта в решение, а затем добавить снова.
Это раздражает и пустая трата времени, но это наименее дорогой из всех других вариантов, которые я знаю.
надеюсь, что это помогает.
Я думаю, что я решил его удалить галочку в Break all processes when one process breaks в параметрах отладки (первый скриншот op->второй вариант).
Он строился/работал хорошо некоторое время, так как я снял его.
Я использую MySql NET Connector и элементы управления DevExpress в своем проекте. Может быть, один из них не располагал связями, привязками и т. д. ну из-за этого флага beeing активирован.
отредактировано: определенно это работает! Больше нет "невозможно скопировать файл" и нет конструктора форм ошибки.
Кажется, что путем изменения имени сборки проекта устраняется проблема.
Так вместо этого
Я меняю его на этот
обратите внимание, что я только что изменил его с Increment and Recall до Increment_Recall , Я просто убрал пробелы. теперь он работает нормально для меня.
добавить в событие предварительной сборки вашего мастер-проекта taskkill /f /fi "pid gt 0" / im "YourProcess.vshost.EXE-файл"
мой вклад 10 центов.
У меня все еще есть эта проблема иногда на VS 2015 Update 2.
Я обнаружил, что переключение цели компиляции решает проблему.
попробуйте это: если вы находитесь в отладочном коммутаторе для выпуска и сборки, затем вернитесь к отладке. Проблема исчезла.
Я не могу дать решение, чтобы предотвратить это, но вы можете по крайней мере переименовать заблокированный файл (проводник windows или классическое командное окно), а затем скомпилировать/построить. Нет необходимости перезагружать или перезапускать VS201x. С некоторым опытом вы можете добавить сценарий предварительной сборки для удаления старых файлов или переименования, а затем в случае блокировки.
посмотреть этот и другие ответы. В принципе, у вас может быть MSBuild.exe процессов, запущенных в фоновом режиме, потребляя ресурсы. Если у вас есть какие-либо задачи до или после сборки, которые вызывают запуск MSBuild через командную строку, попробуйте добавить флаг "/nr:false" к этой команде. Но опять же, см. предыдущий ответ для более конкретных деталей.
вот что сработало для меня (2>nul 1>nul в конце + выход 0):
Если вы отладка шаблонов T4, а затем это происходит все время. Мое решение (до того, как MS исправит это) будет просто убить этот процесс:
Диспетчер Задач --> Пользователь --> T4VSHostProcess.exe
этот процесс возникает только при отладке шаблона T4, а не при его запуске.
- открыть свойства проекта [ меню > проект > свойства ]
- выбрать вкладку "отладка"
- снимите флажок "Включить процесс размещения visual studio"
- начать отладку [F5]
- вы получите предупреждение безопасности, просто "ok". Позволяет запустить приложение
- остановить отладку.
- установите флажок "Включить процесс размещения visual studio" на вкладке отладка,
- теперь попробуйте начать отладку, вы не увидите ошибку опять
[Работа для меня]
следуйте ниже шаги
- Открыть Диспетчер Задач (Ctrl + Alt + Delete)
- под производительность выберите вкладку выберите ProjectNameOfYours.exe>.
- нажмите на завершить процесс.
- Теперь строить решения.
вышеуказанные шаги разрешили ошибку навсегда :)
это работает для меня :)
этот вопрос был первым результатом при поиске следующая ошибка:
не удалось скопировать файл ". - потому что его не нашли.
при создании в Visual Studio 2013 (обновление 3).
решение: удаление "Productivity Power Tools" в Visual Studio 2013.
в моем случае это был Resharper Unit Tests runner (плюс тесты NUnit, никогда не было такой проблемы с MsTests). После убийства процесса удалось перестроить процесс, не перезапуская ОС или VS2013
Я не знал, что у меня все еще есть отладчик, и пытался построить в том же экземпляре Visual Studio. Как только я остановил отладчик, я смог его построить.
убийство vstest.executionengine.exe process (es) решает эту проблему в 90% случаев для меня. Если это не сработает, то и убийство QTAgent32.exe а затем удаление папок /bin и /obj для рассматриваемого проекта работает.
Это самая раздражающая часть моего рабочего дня. :)
для меня это был антивирус Avast, который не позволит visual studio писать/читать / выполнять файл. Поэтому мне пришлось добавить папку Visual studio 2010/2012 в список исключений антивируса. И сразу после этого баам. это работает.
убедитесь, что U закрыть все экземпляры wcfSvcHost и попробуйте снова. У меня получилось!
Я заметил некоторые ответы, которые решили мою проблему, но, на всякий случай, у кого-то есть та же проблема, что и у меня.
ЕСЛИ ВЫ ИСПОЛЬЗУЕТЕ КОНСОЛЬНОЕ ПРИЛОЖЕНИЕ: ПРЕЖДЕ ЧЕМ ДЕЛАТЬ ЧТО-ЛИБО ЕЩЕ.
убедитесь, что вы закрыли все окна консоли, которые могли быть открыты из предыдущей сборки. Например, я просто тестировал какой-то код в консольном приложении, я не понял, что окно консоли с одного из предыдущих раз, когда я запускал свою программу, было открыто. За это сеанс я отлаживал, окно было задвинуто назад, и я не мог его видеть. Просто говорю, что это может быть ваша проблема, поэтому проверьте, чтобы убедиться, что это не проблема.
(невозможно скопировать файл " objDebugProject1.exe " to " binDebugProject1.исполняемый." Процесс не может получить доступ к файлу " binDebugProject1.exe', потому что он используется другим процессом.)
. поэтому я должен закрыть процесс из Диспетчера задач. мой проект-это только одна форма и нет многопоточности.
Что такое решение (без перезапуск VS или убийство процесса)?
этот код ошибки мы как мы можем решить эту проблему?
@Udpate: с тех пор, как я впервые разместил этот "ответ", я склоняюсь к другому объяснению проблемы. Проблема с тех пор, чем это происходило все чаще и чаще за пределами Visual Studio также-при попытке скопировать.EXE файл из одной папки в другую. Хотя в первую очередь Windows не позволяла копировать(!) -. exe-файл (сначала он просил меня об административных правах, но отказался копировать его после этого) он все равно появился в проводнике. Но через какое - то время-без дальнейших разговоров. предприняв какие-то действия, она исчезла волшебным образом. Так же, как проблема в вопросе всегда, кажется, решает себя через некоторое время. Поэтому я предполагаю, что проблема больше связана с отложенным удалением выходного файла проекта и меньше багги VS. Прошу прощения за необоснованные подозрения. :|
Это дает поиск решения в совершенно другом направлении, я думаю. Нашел эту ссылку и обновит о любом прогрессе:
Это известная ошибка в VS. Я обнаружил это очень часто-в основном в VS2010 (с/без SP1). Рекомендуется несколько "решений". Некоторые из них, которые вроде как помогли мне:
- удалить .suo файл в папку проекта. В конце концов, нужно создать целое решение с нуля.
- закрыть все конструкторы Windows Form могут оставаться открытыми.
- используйте сценарий prebuild, который удаляет цель из выходного каталога.
- отключите процесс размещения VS.
ни один из них не исправляет ошибку. Но это может вернуть VS в полезное состояние-пока истинное решение не будет предоставлено MS (если когда-либо будет.)
Я могу подтвердить, что эта ошибка существует в VS 2012 Update 2.
- чистое решение (и ничего больше)
- закройте все открытые документы/файлы в растворе
- выход против 2012
- запустить VS 2012
- Построить Решение
что-то рассмотреть . ищите связанные файлы между проектами в одном решении.
Это должно работать.
перейдите к свойствам проекта. Внутри событий сборки в командной строке события Pre-build добавьте эти две строки кода:
Если вы посмотрите в каталоге obj, и вы не видите своего .exe, возможно, что Avast! или другой антивирус удаляет его. Я бы на самом деле увидеть .exe появляется, а затем исчезает. Как только я выключил Avast! проблема решена.
реальная проблема не в ошибке, которую вы получаете; это то, что приложение не очищается после себя.
Это либо удержание ссылок, а не освобождение ресурсов, либо что-то еще, что заставляет процесс не заканчиваться, когда ему говорят закрыть. Исправьте эту проблему, и проблема разрешится сама собой. Мы не можем помочь вам в этом, если вы не опубликуете свой код (и на данный момент, если вам нужна помощь в этом, вы должны начать новый вопрос).
это происходит потому, что [yourProjectName].exe процесс не закрывается после завершения отладки.
существует два решения этой проблемы.
каждый раз, когда вы вносите изменения в приложение, перейдите в Диспетчер задач -> процессы -> [yourProjectName].exe, завершите этот процесс. Вы должны заканчивать этот процесс каждый раз, когда вносите изменения в систему.
добавить кнопку выхода в приложении, чтобы выйти из окна и добавить эти строки, чтобы нажать событие
Мне пришлось зайти в Проводник windows и удалить папку bin/debug, а также папки obj/debug. Затем я очистил и перестроил проект.
после просмотра аналогичной ошибки в visual studios 2012 из ниоткуда. Я обнаружил, что, перейдя в корневую папку проекта и щелкнув правой кнопкой мыши по нему, я снял флажок только для чтения, и эта ошибка исчезла. По-видимому, TFS иногда делает папку только для чтения. Надеюсь, это поможет любому с подобной проблемой. Спасибо
Это случилось со мной на VS 2010 и Win 7.. Дело:
- Я не могу перестроить с помощью Debug Configuration manager, но я могу перестроить с помощью Release Configuration manager
- проверьте мой тип учетной записи на панели управления-учетная запись пользователя -> Моя учетная запись-Администратор
остановить антивирус, проверить нелепую запущенную программу с помощью Диспетчера задач и ProcessExplorer
Читайте также: