Невозможно найти исполняемый файл компилятора csc exe
Самой очевидной причиной является отсутствие Visual Studio 2010 или какой-то другой графической IDE-среды.
Работа может выполняться в университете, где использование инструментов для генерации кода и IDE-сред обычно запрещено.
Планируется применение автоматизированных средств разработки, таких как msbuild.exe, которые требуют знать опции командной строки для используемых инструментов.
Указание целевых входных и выходных параметров
Первым делом важно разобраться с тем, как указывать имя и тип создаваемой сборки (т.е., например, консольное приложение по имени MyShell.exe, библиотека кода по имени MathLib.dll или приложение Windows Presentation Foundation по имени Halo8.ехе). Каждый из возможных вариантов имеет соответствующий флаг, который нужно передать компилятору csc.ехе в виде параметра командной строки.
Обратите внимание, что параметры, передаваемые компилятору командной строки (а также большинству других утилит командной строки), могут сопровождаться префиксом в виде символа дефиса (-) или слеша (/).
Параметр | Описание |
---|---|
/out | Этот параметр применяется для указания имени создаваемой сборки. По умолчанию сборке присваивается то же имя, что у входного файла *.сs |
/target:exe | Этот параметр позволяет создавать исполняемое консольное приложение. Сборка такого типа генерируется по умолчанию, потому при создании подобного приложения данный параметр можно опускать |
/target:library | Этот параметр позволяет создавать однофайловую сборку *.dll |
/target:module | Этот параметр позволяет создавать модуль. Модули являются элементами многофайловых сборок |
/target:winexe | Хотя приложения с графическим пользовательским интерфейсом можно создавать с применением параметра /target: ехе, параметр /target: winexe позволяет предотвратить открытие окна консоли под остальными окнами |
Чтобы скомпилировать TestApplication.cs в консольное приложение TestApplication.exe, перейдите в каталог, в котором был сохранен файл исходного кода (с помощью флага cd) и введите следующую команду:
Теперь можно попробовать запустить приложение TestApplication.ехе из командной строки, введя имя его исполняемого файла:
haydenhancock commented Jun 12, 2017
@dlarkin77 Take a look at the script below. The only thing you should need to change is the location of the bin directory. Let me know if you have any questions.
pvcove commented Aug 16, 2017
I encountered my errant condition on my Mac. Running VS 2017 Community for Mac OSx. May I ask, ItWorksOnMyMachine, did you experience the error on a Mac or Windows?
pvcove commented Aug 15, 2017
I wrestled with this problem for at least two hours, and I'm referring specifically to the message in the title of this page. The next day I installed the latest Visual Studio updates for Mac and the problem went away. I didn't do a thing to fix it.
Coincidentally, I discovered that the latest release of VS 2017 for Mac became available the very day I performed my VS updates. That said, I recommend installing the latest updates to your Visual Studio 2017 Community for Mac. The release that fixed my problem is Visual Studio for Mac 7.1.0.1297. Refer to the link below
ItWorksOnMyMachine commented Aug 15, 2017
I upgraded VS2017 to Release 2 and performed a bunch of nuget updates and got this problem. I undid all the changes and then just upgraded the Microsoft.CodeCom.Providers.DotNetCompilerPlatform from 1.0.5 to 1.0.6. After the upgrade I stopped getting a roslyn folder in my bin folder. I reverted to 1.0.5 and started getting the folder again.
Jinhuafei commented Dec 29, 2016
CodeDOM Providers is not open source yet, so I'll open a bug in internal TFS and take a look at the issue. Will keep you posted through this issue.
coder-zzo commented Jun 13, 2017
I encounter the problem on Apache 2 with mod_mono in raspberry 2.
I followed a stackoverflow post to added below into vHost config
MonoSetEnv [your-host-name] MONO_IOMAP=all
venky76v commented Mar 28, 2017
Jinhuafei commented Mar 27, 2017
BTW, DotNetCompilerPlatform is open sourced now. If you have any issue, feel free to open an issue on this repo.
hendrikbar commented Dec 9, 2017
Upgrading to Microsoft.CodeDom.Providers.DotNetCompilerPlatform to 1.08 fixed it for me
haydenhancock commented Jan 30, 2017 •
@jaredpar @Jinhuafei Just for the record, I did upgrade the packages to the latest versions for:
Some of the people mentioned that this resolved their issue but it did not resolve mine. Is there anything else I can do to prevent these 26 dlls from being built in the bin directory as a temporary workaround?
The following items are found in my csproj file (using the default MVC template in Visual Studio 2015:
Компиляция нескольких файлов исходного кода
Изменим исходный класс TestApplication так, чтобы в нем использовался класс этого нового типа:
Вывод, получаемый после запуска этой программы, идентичен предыдущей программе. Единственное отличие между этими двумя приложениями связано с разнесением логики по нескольким файлам.
В случае необходимости допускается также указывать и несколько ответных *.rsp файлов в качестве входных параметров (например, csc @FirstFile.rsp @SecondFile.rsp @ThirdFile.rsp). При таком подходе, однако, следует иметь в виду, что компилятор обрабатывает параметры команд по мере их поступления. Следовательно, аргументы командной строки, содержащиеся в поступающем позже файле *.rsp, могут переопределять параметры из предыдущего ответного файла.
Стоит отметить, что в случае добавления с помощью опции /r ссылок на сборки, которые на самом деле не используются, компилятор их проигнорирует. Поэтому беспокоиться по поводу "разбухания кода" не нужно.
CSharpCodeProvider. Ошибка "Невозможно найти исполняемый файл компилятора csc.exe."
Мне необходимо было написать программу, одна из задач - можно редактировать код самой же этой.
Ошибка при попытке запуска проекта: Не удалось загрузить файл или сборку
using System; using System.Threading; namespace Потоки__использующие_один_объект < class.
Не получается компиляция csc.exe
Здравствуйте! Пробую скомпилировать файл TestApp.cs, который лежит в папке C:\MyApplication. В.
Добавлено через 9 минут
Joshim, или воспользуйтесь командной строкой Visual Studio
Скажите как одним движением с компилировать и запустить сразу программу?
что в .bat файле поменять нужно или прописать?
В данный момент можно выполнить двумя действиями сначала запускаешь файл в .bat создается файл в .exe(т.е. это как 1-е действие), Потом нужно ввести в командной строке тот файл который был создан в .exe(2-е действие)
Файл .exe переименовываем в csc.exe и кидаем в папку C:\Windows (нужны права администратора) и теперь если в командной строке написать csc и имя файла .cs то он скомпилируется через csc.exe и поместится в папку в которой вы вызывали его компиляцию.
AlexeyLim, неудачное решение и к тому же неверное решение. Во-первых вместо своего exe в папке Windows проще добавить нужный каталог в переменную PATH. Во-вторых приведенный скрипт передает только один аргумент, а их может быть больше одного. Ну и ситуация когда аргументов нет не обрабатывается.
Как откомпилировать с помощью csc.exe?
Как с помощю csc.exe из program.cs получить program.exe?
Использование файла ресурсов скомпилированного через csc.exe
Цель создать приложение с внедренными ресурсами, а потом при запуске приложения скопировать ресурсы.
Ошибка запуска файла справки в exe файле
Здравствуйте! Возникла проблема. Есть приложение и есть файл справки, который в проекте выводится.
У меня есть сайт, который был и работает:
- ASP.NET 4
- MVC 3
- Entity Framework 4.3
- Запуск в веб-роли Azure (я заметил, что это osFamily = "1", что странно, как я ожидал, будет 2 - но в любом случае . )
- Пакет SDK для Azure 1.7
Я обновил всю свою кодовую базу, чтобы быть в курсе множества новых игрушек. Итак, теперь это:
- ASP.NET 4.5
- MVC 4 (Razor 2)
- Entity Framework 5
- Для конфигурации Azure задано значение osFamily = "3".
- Azure SDK 1.8 (с кропотливым обновлением клиентской библиотеки хранилища до 2, а не до версии 1.7)
Когда я захожу на сайт в промежуточном режиме, я получаю желтый экран смерти с надписью Не удается найти исполняемый файл компилятора csc.exe . У меня вопрос: Почему?
ОБНОВЛЕНИЕ:
OsFamily = "3" имеет только .NET 4 и 4.5, поэтому я предполагаю, что это причина ошибки, но я не прав насчет таргетинга? Я хочу использовать osFamily = "3", что я могу здесь сделать?
Трассировка стека
Хорошо, Дэвид Эббо указал мне правильное направление, и я начал внимательно изучать Entity Framework Profiler. Об этом есть здесь ветка.
Что-то в том, что он создает сборку во время выполнения, и казалось бы, что osfamily = "3" (Server 2012) не позволяет этого (это работало на osfamily = "2" (Server 2008 R2)). Больше не собираюсь отлаживать, так как мне все равно не нужен профилировщик в моей живой среде. Удаление EF Profiler заставило его работать.
У меня была аналогичная проблема с изображением AWS windows server 2019.
Так что нужно было просто удалить это - по-видимому, чтобы он компилировался с любой версией фреймворка, которая используется в то время.
Да, если у вас есть Server 2012, вы определенно используете Fx 4.5, а не 4.0, поскольку это обновление на месте.
Поэтому я подозреваю, что эти старые сборки не являются корнем вашей проблемы.
У меня была аналогичная проблема. Убедитесь, что вы выбрали правильный компилятор. Я нацелился на v4.5 (но должна быть v4.0, так как теперь есть компилятор 4.5)
Как скомпилировать и запустить файл .cs из окна командной строки?
Для запуска сначала откройте командную строку, нажмите «Пуск», затем введите cmd.exe .
Затем вам может потребоваться cd в каталог, в котором хранятся ваши исходные файлы.
(все в одной строке)
Если у вас есть более одного исходного модуля для компиляции, вы можете поместить его в ту же командную строку. Если у вас есть другие сборки для ссылки, используйте /r:AssemblyName.dll .
Убедитесь, что в одном из ваших классов определен статический метод Main (), который действует как «точка входа».
Чтобы запустить полученный EXE-файл, введите MyApplication , а затем в командной строке.
Эта статья на MSDN содержит более подробную информацию. о параметрах компилятора командной строки. Вы можете встраивать ресурсы, устанавливать значки, подписывать сборки - все, что вы могли делать в Visual Studio.
Если у вас установлена Visual Studio, в меню «Пуск»; в инструментах Visual Studio вы можете открыть «командную строку Visual Studio», в которой будут настроены все необходимые переменные среды и пути для компиляции из командной строки.
Хотя это очень удобно, вы должны сочетать это со знанием какого-либо инструмента сборки, такого как NAnt. , MSBuild, FinalBuilder и т. д. Эти инструменты обеспечивают полную среду сборки, а не только базовый компилятор.
Jinhuafei commented Jan 3, 2017
@Sc0tTyXL @Hilgo Is it possible to share a simple repro solution with me? I tried both web site project and web app project with a uncompilable class lib project, but didn't see the issue you mentioned.
Jinhuafei commented Jan 5, 2017
In web app project, DotNetCompilerPlatform nupkg uses msbuild system to copy Roslyn compiler bits to the bin folder. If Roslyn bits somehow is deleted, you need to build the project in order to get Roslyn compiler bits back. Be aware of the msbuild optimization. It won't compile the project, if none of the files is touched in that project. In this scenario, you have to force a rebuild.
So this doesn't look like an issue to me. @Sc0tTyXL @Hilgo Do you mind closing this thread?
Jinhuafei commented Mar 27, 2017
Hilgo commented Dec 28, 2016
@Sc0tTyXL Yes, thanks for the response, i'll keep an eye in the bin folder for roslyn in the future.
Sc0tTyXL commented Dec 28, 2016 •
It seems that 1.0.3. has the same issue as well, I've updated my post.
На Mac
На Mac синтаксис аналогичен, только компилятор C Sharp называется просто csc :
Затем для его запуска:
Скопируйте в эту переменную следующий путь:
"C: \ Windows \ Microsoft.NET \ Framework \ v4.0.30319"
Таким образом, вам не нужно указывать весь путь каждый раз, когда вы компилируете код. Просто используйте
"C: \ Users \ UserName \ Desktop> csc [параметры] filename.cs"
Или где бы ни был путь вашего кода.
Теперь можно идти.
c:> csc Hello.cs
Вы можете запустить программу
c:> Здравствуйте
Для последней версии сначала откройте окно Powershell, перейдите в любую папку (например, c:\projects\ ) и запустите следующую команду
Наконец - обратите внимание, что командная строка зависит от реализации; для MS это csc ; для моно это gmcs и друзья . Аналогично, для выполнения: это просто exename для версии MS, но обычно" mono exename "для mono.
Наконец, многие проекты создаются с помощью инструментов сценария сборки; MSBuild, NAnt и т. д.
Тогда просто беги
"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\Roslyn\csc.exe" MyApplication.cs
Для компиляции единого исходного файла в исполняемый файл.
Вы можете создавать файлы классов в командной строке VS (чтобы были загружены все необходимые переменные среды), а не в командном окне Windows по умолчанию.
Чтобы узнать больше о создании командной строки с помощью csc.exe (компилятор), см. это статья.
Если вы установили Visual Studio, у вас есть командная строка разработчика для VS. Вы можете легко создать свою программу с помощью команды csc и запустить приложение с именем приложения в командной строке разработчика.
Steps to Reproduce:
Project containing a Web site project, a Class library project, a Unit test project and a Windows form project.
(Untested but I suspect a simple Web project + Class library will have the same issues)
- Check bin\roslyn\ folder is not empty
- Make sure the Solution won't be able to build the Test or Windows form project.
A simple compile error should do the trick - Build the solution (must fail)
- The bin\roslyn\ folder is empty
Expected Behavior:
Expect the roslyn compiler to always be there after a successful build.
Actual Behavior:
A rebuild of the Web site project is required to get the Roslyn compiler in the bin\roslyn\ folder. A normal build will not bring back the Roslyn compiler.
The text was updated successfully, but these errors were encountered:
eman1986 commented Dec 19, 2017
Jinhuafei commented Jan 30, 2017
@jaredpar DotNetCompilerPlatform is only for runtime compilation(e.g. aspx/cshtml/global.asax etc..) and it calls Roslyn compiler under bin\roslyn directly. All its nupkg installation steps are just to make sure Roslyn compiler assemblies copied to bin folder.
@haydenhancock Thanks for the link. The problem seems caused by different definition of $(OutDir) on the CI machine. I'll take a look and see what we can do.
jaredpar commented Jan 30, 2017
and it calls Roslyn compiler under bin\roslyn directly
Great. That removes a potential bug I was worried we may have here.
jaredpar commented Jan 30, 2017 •
@Jinhuafei does the DotNetCompilerPlatform nuget use csc directly or does it drive compilation via MSBuild. If it's the latter then that would explain the behavior @haydenhancock is seeing. Also means we likely need to change the package to account for this.
Well, unfortunately, we don't believe installing Visual Studio on a build server is the answer.
Very much agree. Should not be required.
Jinhuafei commented Aug 18, 2017
@fonbrauzen would you please provide more details on this thread?
Pilchie commented Dec 12, 2016
@jaredpar is this related to the NuGet package that pulls in the Roslyn compiler for WebSites? Can you help redirect?
haydenhancock commented Feb 1, 2017 •
@Jinhuafei Definitely something with the OutDir. Here is my MSBuild argument in the MSBuild step in my version of TFS.
Is there a way I can prevent the dlls for roslyn from being in the bin folder?
fonbrauzen commented Aug 18, 2017
same issue on 1.0.7, currently reverted on 1.0.5
wpsmmb commented Feb 8, 2018 •
haydenhancock commented Jan 30, 2017 •
@Jinhuafei This is still an issue for those of us that are using the MSBuild step in Team Foundation Server. I am using TFS 2015 with Update 3 and it appears that the bits for roslyn are put into the bin directory, instead of the bin/roslyn directory. This causes an issue when you try to deploy the app to IIS.
What's interesting is that when building the project locally, it seems to work as expected. The roslyn bits are created in the bin/roslyn directory. I am sure the obvious answer is to just use the Visual Studio build step. Well, unfortunately, we don't believe installing Visual Studio on a build server is the answer.
This Stack Overflow was helpful but unfortunately it just copies the bits into the correct folder so now we have duplicate roslyn files in both the bin and bin/roslyn directories.
ceyhunn commented Jan 31, 2017
Could not find file "(project-path)/bin\roslyn\csc.exe", because of both windows and linux slashes , but there exists this file.
Please help me how I fix this problem?
I am using Archlinux, Mono Develop 6.2
Добавление ссылок на внешние сборки
Далее в командной строке нужно проинформировать компилятор csc.exe о том, в какой сборке содержатся используемые пространства имен. Поскольку применялся класс MessageBox из пространства имен System.Windows.Forms, значит, нужно указать компилятору на сборку System.Windows.Forms.dll, что делается с помощью флага /reference (или его сокращенной версии /r):
Кстати, как поступить, когда необходимо указать csc.exe несколько внешних сборок? Для этого нужно просто перечислить все сборки через точку с запятой. В рассматриваемом примере ссылаться на несколько сборок не требуется, но ниже приведена команда, которая иллюстрирует перечисление множества сборок:
csc /r:System.Windows.Forms.dll;System.Drawing.dll *.cs
Sc0tTyXL commented Jan 4, 2017
I tried to create a new solution and make it 100% reproducible but sadly I can't.
The only thing I can say for certain is that when I empty the Roslyn folder manually, a normal build then never fills the folder, a rebuild is always required.
I suspect that something else is clearing the folder which would explain why I can't reproduce it in a empty solution.
Hilgo commented Dec 27, 2016
I am also facing this problem with the project not being able to find 'bin\roslyn\csc.exe', saw some tips in how to solve them, but in my case, this problem sometimes stopped happening when i rebuild and initialize the project a couple times, only to show up again later, when i make changes in my application.
I know this is not linked to this problem, i just wanted to know where to look for it, i guess is something related to IIS and my ApplicationPool in my machine.
dlarkin77 commented Jun 12, 2017
@haydenhancock I've been fighting with the answers in that SO thread and so far none of them are working for me. Could I get a look at your Powershell script?
dlarkin77 commented Jun 12, 2017
@haydenhancock Excellent. Thanks very much.
Hilgo commented Jan 4, 2017
@Jinhuafei , i wouldn't know where to start to isolate the problem to do a repro solution, the solution i work with has a lot of libraries and is not happening anymore, rebuilding the solution worked for me and since that, roslyn folder is always there.
venky76v commented Mar 27, 2017
Hi Jin, Thanks for your reply. Why is the roslyn folder copied to the bin folder on the IIS server where the app is installed. I mean, is there a real need for it? We started getting errors on IIS because of the folder and when we uninstalled a couple of nuget packages, and re-deployed, the app started working again.
Regards,
Venky
pauledrupt commented Aug 16, 2017
same here, reverted to 1.0.5 and all ok
jaredpar commented Dec 12, 2016
ItWorksOnMyMachine commented Aug 16, 2017
My issue is on Windows. It was happening on my local dev machine, on our build server , and ultimately on the server hosting the deployed website in iis.
Pilchie commented Dec 27, 2016
@Jinhuafei what's the right place for this to be reported/investigated?
Kash3580 commented Sep 15, 2017
haydenhancock commented Apr 8, 2017
- set bin directory
- remove all items
- copy all dlls
- copy roslyn folder
Let me know if you are interested in the script and I will send it over.
venky76v commented Mar 27, 2017
Why do we need this roslyn folder in the bin folder? what does it do?
Jinhuafei commented Mar 28, 2017
Roslyn compiler provides a lot of benefits compared to old compilers. (check out this blog)
Yes, in VS 2015 we updated web application project template to include DotNetCompilerPlatform nupkg. If you don't need it, you can definitely remove this nupkg, and the app will switch back to use the old compilers.
glmblue commented Dec 22, 2017
I found that installing dsx's Microsoft.CodeDom.Providers.DotNetCompilerPlatform.BinFix package worked for me:
Читайте также: