[c#] Could not find a part of the path ... bin\roslyn\csc.exe

I am trying to run Asp.net MVC project retrieved from TFS source control. I have added all assembly references and I am able to build and compile successfully without any error or warning.

But I get the following error in the browser:

Could not find a part of the path 'C:\B8akWorkspace\B8akProject\B8akSolution\B8AK.Portal\bin\roslyn\csc.exe'.

Here is a full screenshot of the error page.

enter image description here

After few days of research, I understood that Roslyn is .Net compiler platform that offers advance compiling features. However, I do not understand why my build is trying to find \bin\roslyn\csc.exe because I did not configure anything related to Roslyn nor I intend to use Roslyn in my project.

This question is related to c# asp.net .net asp.net-mvc roslyn

The answer is


TL; DR

run this in the Package Manager Console:

Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r

More information

This problem is not related to Visual Studio itself, so answers suggesting adding build steps to copy files over are rather a workaround. Same with adding compiler binaries manually to the project.

The Roslyn compiler comes from a NuGet package and there is/was a bug in some versions of that package (I don't know exactly which ones). The solution is to reinstall/upgrade that package to a bug-free version. Originally before I wrote the answer back in 2015 I fixed it by installing following packages at specific versions:

  • Microsoft.Net.Compilers 1.1.1
  • Microsoft.CodeDom.Providers.DotNetCompilerPlatform 1.0.1

Then I looked into .csproj and made sure that the paths to packages are correct (in my case ..\..\packages\*.*) inside tags <ImportProject> on top and in <Target> with name "EnsureNuGetPackageBuildImports" on the bottom. This is on MVC 5 and .NET Framework 4.5.2.


Your build is trying to find \bin\roslyn\csc.exe because the following packages have been added to your project. Just review your packages.config file, you can have both of them there

Microsoft.CodeDom.Providers.DotNetCompilerPlatform
Microsoft.Net.Compilers

What is Roslyn and Who added them(packages) in the project : If you’re using .net Framework 4.5.2 to create projects using VS2015, you might have noticed that the project templates use Roslyn by default. Actually Roslyn is one of open-source compilers for .NET languages from Microsoft.

Why should we delete Roslyn : If your project has Roslyn references and you are interested to deploy it no server, you will get unwanted errors on the website as many hosting providers still have not upgraded their servers and hence do not support Roslyn. To resolve this issue, you will need to remove the Roslyn compiler from the project template.

if you are not interested in using Roslyn, follow steps bellow to delete it

1. Remove NuGet packages, use the following commands from Nuget Package Console

PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
PM> Uninstall-package Microsoft.Net.Compilers

2. After you do this, your web.config file should be auto-updated. In case it is not, look for the below code in web.config file and if it is found, delete this piece of code.

<system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"></compiler>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"></compiler>
    </compilers>
</system.codedom>

A clean and rebuild worked for me!


Here is a more MSBuild way of doing this.

<Target Name="CopyRoslynFiles" AfterTargets="AfterBuild" Condition="!$(Disable_CopyWebApplication) And '$(OutDir)' != '$(OutputPath)'">
    <ItemGroup>
      <RoslynFiles Include="$(CscToolPath)\*" />
    </ItemGroup>
    <MakeDir Directories="$(WebProjectOutputDir)\bin\roslyn" />
    <Copy SourceFiles="@(RoslynFiles)" DestinationFolder="$(WebProjectOutputDir)\bin\roslyn" SkipUnchangedFiles="true" Retries="$(CopyRetryCount)" RetryDelayMilliseconds="$(CopyRetryDelayMilliseconds)" />
</Target>

But I notice that the roslyn files are also in my bin directory (not in a folder). The app seems to work, though.


As noted in an issue in the Roslyn project on GitHub, a solution (that worked for me) is to simply unload and reload the project in Visual Studio.

The "bin\roslyn" folder wasn't created on build or rebuild until I reloaded the project.


I followed these steps and it worked perfectly

  • Delete all the bin and obj folders
  • Clean solution and rebuild
  • Run this command in powershell

Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r


Too late for an answer but still posting incase it helps anyone.
Following the below steps fixed the error for me:

  1. delete packages folder
  2. open VS
  3. rebuild
  4. observe that NuGet packages are restored, but bin\roslyn isnt created
  5. unload project
  6. reload project
  7. rebuild
  8. observe that the bin\roslyn has been created now.

I was also having same issue while running the project. Here are the steps that I followed.

  1. Right click in solution
  2. select Clean solution
  3. After clean succeeded,Again build your project
  4. Run the project again

This time I didn't see the same error. This works as expected.


After trying all of the fixes with no cigar I fixed it by updating this Nuget Package in Visual Studios:

Microsoft.CodeDom.Providers.DotNetCompilerPlatform

Mine was from 1.0.0 to 2.0.0 for reference (The error no longer shows)


  1. Clean Solution
  2. Rebuild Solution ,These two steps worked for me.

NuGet Package Manager

You need to install Microsoft.CodeDom.Providers.DotNetCompilerPlatform.BinFix, was especially created for that error


As already noted by https://stackoverflow.com/questions/32780315#34391473, the quick fix is to use the package manager, Tools > Nuget Package Manager > Package Manager Console, to run

Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r

Packet Manager Console - how to open

But an alternative solution (which automatically and silently recreates your packages if they are missing) is to remove an attribute of your project's Web.config file.
(Web.config is in the same directory as your .csproj file.)

Open the Web.config file in a text editor (or inside Visual Studio).
- In the tag configuration > system.codedom > compilers > compiler language="c#;cs;csharp", completely remove the type attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- ... -->
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>

In short, remove the line that starts with type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.

(Presumably, the same fix works for Visual Basic as well as for Csharp, but I have not tried it.)

Visual Studio will take care of the rest. No more Server Error in '/' Application.

In the example code I provided in the zip file above you will now get HTTP Error 403 when you hit Ctrl+F5.

HTTP Error 403.14 - Forbidden

Try replacing http://localhost:64195 in your web browser with http://localhost:64195/api/products.
The web API now displays as it should:

A web API containing products

As a provocation, I tried removing the whole package directory of my Visual Studio solution.
It was automatically and silently recreated as soon as I (re-)built it.


Last but not least, here is code that reproduces the error: http://schulze.000webhostapp.com/vs/SrvrErr-reproduce.zip (Originally from https://github.com/aspnet/AspNetDocs/tree/master/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client/sample/server/ProductsApp)

Server Error


  • Right click on your project and select Manage Nuget Packages
  • Find "Microsoft.CodeDom.Providers.DotNetCompilerPlatform"
  • Simply Update to an older or newer version (doesn't matter which), and then update again back to your original version.

This re-installs all the dependencies and files of the package (like csc.exe)

Nuget - DotNetCompilerPlatform


For VS 2019 remove the following node completely:

<system.codedom>
</system.codedom>

In my case, before trying any of the other solutions, I switched to a "Release" configuration, rebuilt (the folder got created) and then switched back to "Debug", while the folder remained intact.

This was a checkout from source control of an older solution and apparently the original (automatic) package restore and building the project didn't create that folder in the bin directory.

Note that at time of writing this, the blamed component has reached v.2.


So, Rob Cannon's answer essentially worked for me, but I had to tweak a handful of the options. Specifically, I had to remove the condition on the target, as well as change the Include attribute, as $CscToolPath was empty when the project was being built on our build server. Curiously, $CscToolPath was NOT empty when running locally.

<Target Name="CopyRoslynFiles" AfterTargets="AfterBuild" >
  <ItemGroup>
    <RoslynFiles Include="$(SolutionDir)packages\Microsoft.Net.Compilers.1.1.1\tools\*" />
  </ItemGroup>
  <MakeDir Directories="$(WebProjectOutputDir)\bin\roslyn" />
  <Copy SourceFiles="@(RoslynFiles)" DestinationFolder="$(WebProjectOutputDir)\bin\roslyn" SkipUnchangedFiles="true" Retries="$(CopyRetryCount)" RetryDelayMilliseconds="$(CopyRetryDelayMilliseconds)" />
</Target>

This is a known issue with Microsoft.CodeDom.Providers.DotNetCompilerPlatform 1.0.6. Downgrading to 1.0.5 fixed this for me.


Updating nuget packages worked for me Right click on the solution > Manage NuGet packages for solution and update all the packages and specially: Microsoft.Net.Compilers and Microsoft.CodeDom.Providers.DotNetCompilerPlatform


Per a comment by Daniel Neel above :

version 1.0.3 of the Microsoft.CodeDom.Providers.DotNetCompilerPlatform Nuget package works for me, but version 1.0.6 causes the error in this question

Downgrading to 1.0.3 resolved this issue for me.


In my case I have had issue in Jenkins when it tried to deploying it in Octopus with following error:

MSBUILD : OctoPack error OCT-1676060969: Failed to build the path for '\bin\roslyn\csc.exe' relative to 'T:\workspace\machine.engine\Machine.engine.Test': Invalid URI: The format of the URI could not be determined.. See the inner exception for more details. [T:\workspace\machine.engine\Machine.engine.Test\Machine.engine.Test.csproj]
MSBUILD : OctoPack error OCT-1676060969: System.Exception: Failed to build the path for '\bin\roslyn\csc.exe' relative to 'T:\workspace\machine.engine\Machine.engine.Test': Invalid URI: The format of the URI could not be determined.. See the inner exception for more details. ---> System.UriFormatException: Invalid URI: The format of the URI could not be determined. [T:\workspace\machine.engine\Machine.engine.Test\Machine.engine.Test.csproj]
MSBUILD : OctoPack error OCT-1676060969:    at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind) [T:\workspace\machine.engine\Machine.engine.Test\Machine.engine.Test.csproj]
MSBUILD : OctoPack error OCT-1676060969:    at System.Uri..ctor(String uriString) [T:\workspace\machine.engine\Machine.engine.Test\Machine.engine.Test.csproj]
MSBUILD : OctoPack error OCT-1676060969:    at OctoPack.Tasks.Util.OctopusPhysicalFileSystem.GetPathRelativeTo(String fullPath, String relativeTo) in Z:\buildAgent\workDir\20ba9f2e0d5e4022\source\OctoPack.Tasks\Util\OctopusPhysicalFileSystem.cs:line 211 [T:\workspace\machine.engine\Machine.engine.Test\Machine.engine.Test.csproj]
MSBUILD : OctoPack error OCT-1676060969:    --- End of inner exception stack trace --- [T:\workspace\machine.engine\Machine.engine.Test\Machine.engine.Test.csproj]
MSBUILD : OctoPack error OCT-1676060969:    at OctoPack.Tasks.Util.OctopusPhysicalFileSystem.GetPathRelativeTo(String fullPath, String relativeTo) in Z:\buildAgent\workDir\20ba9f2e0d5e4022\source\OctoPack.Tasks\Util\OctopusPhysicalFileSystem.cs:line 224 [T:\workspace\machine.engine\Machine.engine.Test\Machine.engine.Test.csproj]
MSBUILD : OctoPack error OCT-1676060969:    at OctoPack.Tasks.CreateOctoPackPackage.AddFiles(XContainer nuSpec, IEnumerable`1 sourceFiles, String sourceBaseDirectory, String targetDirectory, String relativeTo) in Z:\buildAgent\workDir\20ba9f2e0d5e4022\source\OctoPack.Tasks\CreateOctoPackPackage.cs:line 443 [T:\workspace\machine.engine\Machine.engine.Test\Machine.engine.Test.csproj]
MSBUILD : OctoPack error OCT-1676060969:    at OctoPack.Tasks.CreateOctoPackPackage.Execute() in Z:\buildAgent\workDir\20ba9f2e0d5e4022\source\OctoPack.Tasks\CreateOctoPackPackage.cs:line 190 [T:\workspace\machine.engine\Machine.engine.Test\Machine.engine.Test.csproj]
Done Building Project "T:\workspace\machine.engine\Machine.engine.Test\Machine.engine.Test.csproj" (default targets) -- FAILED

Cause

After spending some time, I was using an internal developed component that was using Microsoft.Net.Compilers. The reason the internal component was using Microsoft.Net.Compilers was to overcome this issue (C#: throw invalid expression compilation) and was solved this way (How to use C# 7 with Visual Studio 2015?). This result in, when I installed the component on the main program, the Microsoft.Net.Compilers get added it selves automatically.

Solution

My work around was, uninstall following from our internal component by (following @malikKhalil answer)

PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
PM> Uninstall-package Microsoft.Net.Compilers

And chose C# 7 compiler in Jenkins instead of C# 6 and rebuild, this is to ensure everything is working and building correctly.

Than finally in my main program I tried to update my internal component. And everything than build again. It has built without any problems or issues.


In my case I just needed to go to the bin directory in Visual Studio Solution Explorer (web application project) and include the roslyn project directly. By right clicking the folder and selecting Include In Project. And check in the solution again to trigger the build process.

The roslyn folder was not included by default.


Upgrading Microsoft.CodeDom.Providers.DotNetCompilerPlatform from 1.0.0 to 1.0.1 fixed this for me.


In my case by just Deleting everything inside the bin folder and recompiling did all the work for me.


Open the project file and remove all references with Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0....

Open web.config and remove all system.codedom compilers attributes


If you were adding ASPNETCOMPILER to compile your Razor views in MVC, like in this StackOverflow question, then change PhysicalPath to place where Roslyn nuget package is located (usually pointed via $CscToolPath variable):

<Target Name="AfterBuild" Condition="'$(MvcBuildViews)'=='true'">
<AspNetCompiler VirtualPath="temp" PhysicalPath="$(CscToolPath)" />


The problem with the default VS2015 templates is that the compiler isn't actually copied to the {outdir}_PublishedWebsites\tfr\bin\roslyn\ directory, but rather the {outdir}\roslyn\ directory. This is likely different from your local environment since AppHarbor builds apps using an output directory instead of building the solution "in-place".

To fix it, add the following towards end of .csproj file right after xml block <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">...</Target>

<PropertyGroup>
  <PostBuildEvent>
    if not exist "$(WebProjectOutputDir)\bin\Roslyn" md "$(WebProjectOutputDir)\bin\Roslyn"
    start /MIN xcopy /s /y /R "$(OutDir)roslyn\*.*" "$(WebProjectOutputDir)\bin\Roslyn"
  </PostBuildEvent>
</PropertyGroup>

Reference: https://support.appharbor.com/discussions/problems/78633-cant-build-aspnet-mvc-project-generated-from-vstudio-2015-enterprise


In my case, similar to Basim, there was a NuGet package that was telling the compiler we needed C# 6, which we didn't.

We had to remove the NuGet package Microsoft.CodeDom.Providers.DotNetCompilerPlatform which then removed:

  1. <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net452" /> from the packages.config file
  2. <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" /> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" /> </compilers> </system.codedom>

In the system.codedom node, you can see why it was bringing in roslyn: compilerOptions="/langversion:6


Delete the Bin folder in your solution explorer and Build the solution again. That would solve the problem


I have webproject without csproj file and solutions mentiond here did not work for me.

Changing target .NET framework, reinstalling packages (Update-Package -reinstall) and then building the project worked for me. You can even change target framework back after this operation(make suere you reinstall nuget packages again after).


I had the same problem when installing my application on the server when everything worked perfectly on localhost.

None of these solutions woorked, I always had the same error:

Could not find a part of the path 'C:\inetpub\wwwroot\myApp\bin\roslyn\csc.exe'

I ended up doing this:

  • on my setup project, right clic, view > file system
  • create a bin/roslyn folder
  • select add > files and add all files from packages\Microsoft.Net.Compilers.1.3.2\tools

This solved my problem.


Reboot Windows.

This is the only solution that worked for me after trying rebuild, delete contents of bin and rebuild, restart Visual Studio.

It's yet another example of how terrible C#/.NET build tools are.

I think (after reading many of the answers), the overall conclusion is that the cause and solution of this problem heavily depends on the setup and project, so if one answer does not work, just try another. Try non-intrusive/destructive solutions, such as restarting Visual Studio, rebooting, rebuilding, etc., FIRST, before messing with NuGet packages or reinstalling development tools. Good luck!

(NOTE: Using Visual Studio 2019, and project file was originally created in Visual Studio 2015. Maybe this helps someone investigate the issue)

(EDIT: Could this be caused by not rebooting after installing/modifying the Visual Studio installation or updating Visual Studio when the installer prompts to reboot?)


Other than deleting the Bin diretory from all projects inside the solution, delete the obj folders too.

In the main solution diretory remove the folder .vs

Worked for me when trying to bring an already done project into a blank solution created on git.


I had this issue on the server I was deploying to, and determined that I did not need

Microsoft.CodeDom.Providers.DotNetCompilerPlatform

So, I uninstalled it via nuget, and removed the reference in the web config. No more issues.

I originally tried to added target node to the .proj file as mentioned in some of the other answers, but that just lead to another error where the msbuild could not copy the pagefile.sys which seemed from what I read to be a bug in the nuget package.


The following solved this issue for me:

  • Updating to the latest version of Visual Studio 2017 (using the installer app)

  • Clean and rebuild the solution


I ran into this problem after updating some packages through NuGet. A rebuild (instead of a normal build) has worked for me.


I had this error for Microsoft.CodeDom.Providers.DotNetCompilerPlatform 1.06 but also with 1.0.7 that worked for @PrisonerZERO. However when Microsoft released 1.0.8 2017-10-18 it finally started working for me again and I did not have to downgrade.

https://www.nuget.org/packages/Microsoft.CodeDom.Providers.DotNetCompilerPlatform/


Add PropertyGroup to your .csproj file

<PropertyGroup>
  <PostBuildEvent>
    if not exist "$(WebProjectOutputDir)\bin\Roslyn" md "$(WebProjectOutputDir)\bin\Roslyn"      
    start /MIN xcopy /s /y /R "$(OutDir)roslyn\*.*" "$(WebProjectOutputDir)\bin\Roslyn"
  </PostBuildEvent>
</PropertyGroup>

my solution is using Nuget to update below items to latest version: - Microsoft.Net.Compilers - Microsoft.CodeDom.Providers.DotNetCompilerPlatform Then rebuilt the project. Since my project is a website so no *.csproj file. The error above appears when I tried to view a cshtml in browser.

The error fixed after the two items above updated to latest version. I am in VS2015 and windows7 SP1


In my case I had this issue when i was running two visual studio IDE simultaneously. So the solution was to clean the project and close the other instance.


I had the same problem after updating DotNetCompilerPlatform. Solved by Restarting Visual Studio > Clean Project > Build Project.


This can be done in the following easy way-:

  • Create a new project of similar type anywhere in your system. Build it and copy over the roslyn folder to your bin directory.

A lot of these answers are referring to the Nuget packages and/or cleaning and reloading your project.

If you have WCF service references and invalid endpoints, you can also get this error message. Make sure your endpoints are correct and update the service configuration with the correct endpoint in the .config and when you configure the service reference from the GUI.

Image of Service Reference Configuration GUI


FYI...

As of 8/31/2017 upgrading to Microsoft.CodeDom.Providers.DotNetCompilerPlatform 1.0.7 is works.


I had to change the WebAPI and MVC project files to not build views:

<MvcBuildViews>false</MvcBuildViews>

This resolved my TFS 2015 Build server error with roslyn. Still not sure why csc.exe was copied to \bin\csc.exe, yet the publish process was looking for \bin\Roslyn\csc.exe...couldn't find the transformation causing that discrepancy.


I had this error after renaming a solution and some included projects, and playing around with removing nuget packages. I compared the new project with the last working project, and found the following lines were missing and needed to be added back in:

  <Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
  <Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />

Doing so resolved the issue for me.


None of the other answers worked for me. After doing a folder compare before/after vs my expected committed files, i discovered that GIT was ignoring a required folder. If you are tracking the compiler in a repository, make sure the BUILD folder is tracked. If it's not, the compiler won't ever be built and will throw this exact error after publish. I added this line to my .gitignore file:

!**/packages/Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1/build/

and now it's deploying to other computers properly.


I ran into this issue with the publishing pipeline (which produces a _PublishedWebsites directory), and used this as a Target in the project:

<Target Name="CopyRoslynCompilerFilesToPublishedWebsitesDirectory" AfterTargets="AfterBuild" Condition="Exists('$(OutDir)\_PublishedWebsites\$(TargetName)')">
    <Copy SourceFiles="@(RoslyCompilerFiles)" DestinationFolder="$(OutDir)\_PublishedWebsites\$(TargetName)\bin\roslyn" ContinueOnError="true" SkipUnchangedFiles="true" />
</Target>

The downside is that there will be two copies of the Roslyn files in the output.


I experienced this error on a Jenkins build server running MSBuild, which outputs the build files to a separate folder location (_PublishedWebsites). Exactly the same - the roslyn folder was not in the bin directory, and all the roslyn files were lumped in with the bin files.

@igor-semin 's answer was the only thing that worked for me (as I am using the C# 6 language features, I cannot simply uninstall the nuget packages as per other answers), but as I am also running CodeAnalysis, I was getting another error on my deployment target server:

An attempt to override an existing mapping was detected for type Microsoft.CodeAnalysis.ICompilationUnitSyntax with name "", currently mapped to type Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax, to type Microsoft.CodeAnalysis.VisualBasic.Syntax.CompilationUnitSyntax.

The reason for this is that as the roslyn files are getting dumped into the main bin directory, when you run the xcopy to recreate them in the nested roslyn folder, you now have 2 copies of these files being compiled and there is a clash between them. After much frustration I decided on a 'hack' fix - an additional post-build task to delete these files from the bin directory, removing the conflict.

The .csproj of my offending projects now looks like:

................... more here ......................

 <PropertyGroup>
   <PostBuildEvent>
   if not exist "$(WebProjectOutputDir)\bin\Roslyn" md "$(WebProjectOutputDir)\bin\Roslyn"
   start /MIN xcopy /s /y /R "$(OutDir)roslyn\*.*" "$(WebProjectOutputDir)\bin\Roslyn"
 </PostBuildEvent>
</PropertyGroup>
<Target Name="DeleteDuplicateAnalysisFiles" AfterTargets="AfterBuild">
   <!-- Jenkins now has copies of the following files in both the bin directory and the 'bin\rosyln' directory. Delete from bin. -->
   <ItemGroup>
     <FilesToDelete Include="$(WebProjectOutputDir)\bin\Microsoft.CodeAnalysis*.dll" />
   </ItemGroup>
   <Delete Files="@(FilesToDelete)" />
</Target>

................... more here ......................


The answer for this is different for Website project and Web application Project. The underlying issue is same that NuGet package is behaving differently on different machine. It may be rights issue or some execution policy which stops it from copying to Bin folder As you know Roslyn is new compiler. you should have it in Bin folder for these Projects Go to your website NuGet Packages check this Folder Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.0 \code\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.0 Do you see it ? Can you see code\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.0\tools\RoslynLatest in it Now as part of compiling this Folder should get copied to your website under bin like this. \code\WebSite1\Bin\Roslyn some how that is not happening for you . Try running Visual studio as Admin . Copy Roslyn folder manually. Try uninstall and install of NuGet Package. Remember this package compile your folder and if its not there you cannot compile anything and so you cannot add anything too. Try copying this package to offline version tools -> options-> nuget package Manager->Package source-> Microsoft Visual Studio Offline Packages C:\Program Files (x86)\Microsoft SDKs\NuGetPackages


In my situation, our team don't want to keep 'packages' folder, so we put all dlls in other directory like 'sharedlib'.

I used build event to solve this problem.

if "$(ConfigurationName)" == "Release" (
goto :release
) else (
goto:exit
)

:release
if not exist $(TargetDir)\roslyn mkdir $(TargetDir)\roslyn

copy /Y "$(ProjectDir)..\..\Shared Lib\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\tools\Roslyn45\*" "$(TargetDir)\roslyn"
goto :exit

:exit

Issue

Be aware that the NuGet PM breaks the Rosalyn behavior. Click Tools > NuGet Package Manager > Manage NuGet Packages for Solution If an update Exists for Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Microsoft.Net.Compilers, or Microsoft.Net.Compilers.netcore, update them and the Solution will break! This occurs because the ASP Sites templates are set to use specific versions at project creation. To See the problem, click Show All Files in the Solution Explorer.

Fix

At project creation the $(WebProjectOutputDir)\bin doesn't exist, therefore when Rosalyn is added as a dependency by NuGet it installs it properly. After Updating the Solution Packages, the $(WebProjectOutputDir)\bin directory looks like so:

$(WebProjectOutputDir)\bin\bin\rosalyn

The easiest fix is to Cut & Paste rosalyn to the proper location, and then delete the extra bin folder. You can now Refresh the page and the site will load.


To prevent the build from also copying the Roslyn files to the bin directory, you have to also comment out this line that gets placed at the top of your Web application project:

<!--  <Import Project="..\..\..\DAS\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.1\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\..\..\DAS\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.1\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" /> -->

Questions with c# tag:

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array How can I add raw data body to an axios request? Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Convert string to boolean in C# Entity Framework Core: A second operation started on this context before a previous operation completed ASP.NET Core - Swashbuckle not creating swagger.json file Is ConfigurationManager.AppSettings available in .NET Core 2.0? No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? How to use log4net in Asp.net core 2.0 Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 Update .NET web service to use TLS 1.2 Using app.config in .Net Core How to send json data in POST request using C# ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response How to enable CORS in ASP.net Core WebAPI VS 2017 Metadata file '.dll could not be found How to set combobox default value? How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac ALTER TABLE DROP COLUMN failed because one or more objects access this column Error: the entity type requires a primary key How to POST using HTTPclient content type = application/x-www-form-urlencoded CORS: credentials mode is 'include' Visual Studio 2017: Display method references Where is NuGet.Config file located in Visual Studio project? Unity Scripts edited in Visual studio don't provide autocomplete How to create roles in ASP.NET Core and assign them to users? Return file in ASP.Net Core Web API ASP.NET Core return JSON with status code auto create database in Entity Framework Core Class Diagrams in VS 2017 How to read/write files in .Net Core? How to read values from the querystring with ASP.NET Core? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? ASP.NET Core Get Json Array using IConfiguration Entity Framework Core add unique constraint code-first No templates in Visual Studio 2017 ps1 cannot be loaded because running scripts is disabled on this system

Questions with asp.net tag:

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Custom Authentication in ASP.Net-Core Custom header to HttpClient request ASP.NET 5 MVC: unable to connect to web server 'IIS Express' IIS Config Error - This configuration section cannot be used at this path Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015 TLS 1.2 in .NET Framework 4.0 The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located Could not find a part of the path ... bin\roslyn\csc.exe CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default Adding ASP.NET MVC5 Identity Authentication to an existing project TypeError: $(...).DataTable is not a function The page cannot be displayed because an internal server error has occurred on server How to get the current logged in user Id in ASP.NET Core When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 No connection could be made because the target machine actively refused it 127.0.0.1 @Html.DisplayFor - DateFormat ("mm/dd/yyyy") How can I validate google reCAPTCHA v2 using javascript/jQuery? How to get DropDownList SelectedValue in Controller in MVC How do I enable NuGet Package Restore in Visual Studio? Specified cast is not valid? Display two fields side by side in a Bootstrap Form variable is not declared it may be inaccessible due to its protection level An unhandled exception occurred during the execution of the current web request. ASP.NET How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2 The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception System.web.mvc missing How to get JSON object from Razor Model object in javascript SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance How to get current domain name in ASP.NET How to return a file (FileContentResult) in ASP.NET WebAPI Select query to get data from SQL Server NuGet: 'X' already has a dependency defined for 'Y' How can I make window.showmodaldialog work in chrome 37? Selecting multiple columns with linq query and lambda expression onchange event for html.dropdownlist Pass multiple complex objects to a post/put Web API method How to update a claim in ASP.NET Identity?

Questions with .net tag:

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface How to decode JWT Token? What's the difference between .NET Core, .NET Framework, and Xamarin? .NET Core vs Mono How to specify the port an ASP.NET Core application is hosted on? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests Build error, This project references NuGet IIS Config Error - This configuration section cannot be used at this path There is no argument given that corresponds to the required formal parameter - .NET Error Could not find a part of the path ... bin\roslyn\csc.exe Can you install and run apps built on the .NET framework on a Mac? What is the purpose of nameof? Microsoft.ReportViewer.Common Version=12.0.0.0 What is the default value for Guid? Authentication failed because remote party has closed the transport stream What is the difference between a Shared Project and a Class Library in Visual Studio 2015? How to break out of the IF statement No connection could be made because the target machine actively refused it 127.0.0.1 Default SecurityProtocol in .NET 4.5 How to properly make a http web GET request What is ".NET Core"? IOException: The process cannot access the file 'file path' because it is being used by another process System.web.mvc missing Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation) SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904) Write to Windows Application Event Log Operator overloading ==, !=, Equals System.Net.WebException: The remote name could not be resolved: Running multiple async tasks and waiting for them all to complete What is an "index out of range" exception, and how do I fix it? Found conflicts between different versions of the same dependent assembly that could not be resolved Getting the first and last day of a month, using a given DateTime object Error 1053 the service did not respond to the start or control request in a timely fashion BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed Download files from SFTP with SSH.NET library An object reference is required to access a non-static member AppendChild() is not a function javascript Send JSON via POST in C# and Receive the JSON returned? Why is HttpClient BaseAddress not working? KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

Questions with asp.net-mvc tag:

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core localhost refused to connect Error in visual studio ASP.NET 5 MVC: unable to connect to web server 'IIS Express' How to use SqlClient in ASP.NET Core? Pass Model To Controller using Jquery/Ajax How can I make my string property nullable? Could not find a part of the path ... bin\roslyn\csc.exe CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default How to remove error about glyphicons-halflings-regular.woff2 not found Adding ASP.NET MVC5 Identity Authentication to an existing project ASP.NET Web API : Correct way to return a 401/unauthorised response Effectively use async/await with ASP.NET Web API The page cannot be displayed because an internal server error has occurred on server Calling Web API from MVC controller Rendering partial view on button click in ASP.NET MVC Bootstrap fixed header and footer with scrolling body-content area in fluid-container Display List in a View MVC Phone Number Validation MVC How to get 'System.Web.Http, Version=5.2.3.0? How to call controller from the button click in asp.net MVC 4 How to extend available properties of User.Identity How to pass multiple parameters from ajax to mvc controller? @Html.DisplayFor - DateFormat ("mm/dd/yyyy") How to get DropDownList SelectedValue in Controller in MVC MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource How to add/update child entities when updating a parent entity in EF Return HTML from ASP.NET Web API Jquery Ajax, return success/error from mvc.net controller There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country System.web.mvc missing How to get JSON object from Razor Model object in javascript error CS0103: The name ' ' does not exist in the current context How to return a file (FileContentResult) in ASP.NET WebAPI Return JsonResult from web api without its properties Using a PagedList with a ViewModel ASP.Net MVC How to call MVC Action using Jquery AJAX and then submit form in MVC? onchange event for html.dropdownlist How to update a claim in ASP.NET Identity? Make sure that the controller has a parameterless public constructor error @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array

Questions with roslyn tag:

Could not find a part of the path ... bin\roslyn\csc.exe