Search code examples
c#.netcompiler-errorsconsole-application

Why "dotnet new console" generates a project that cannot be compiled with "dotnet build"? (error CS5001)


First, a little excerpt from Microsoft:

Starting with .NET 6, the project template for new C# console apps generates the following code in the Program.cs file:

// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

The new output uses recent C# features that simplify the code you need to write for a program.

. . . When you use the newer version, you only need to write the body of the Main method. The compiler generates a Program class with an entry point method and places all your top level statements in that method. The name of the generated method isn't Main, it's an implementation detail that your code can't reference directly. You don't need to include the other program elements, the compiler generates them for you.


Having .NET SDK 8 installed, I opened the command prompt and typed:

dotnet new console --output "D:\User Files\A_L_L\DOWNLOAD_TEMP\test"

It created the project files, one of which is Program.cs. The contents of this file are exactly as described above (in the Microsoft article).

The problem is, I can't build the project. When I type

dotnet build "D:\User Files\A_L_L\DOWNLOAD_TEMP\test\test.csproj" --artifacts-path "D:\User Files\A_L_L\DOWNLOAD_TEMP\test"

the following error is produced:

error CS5001: Program does not contain a static 'Main' method suitable for an entry point

So... looks like the new program style, generated by the new console, cannot be compiled, because the build command expects the old program style (with Main entry point).

What's going on here? How can I compile the project succesfully?

Thanks


Solution

  • Setting --artifacts-path to a project directory breaks the build for some reason; when used, it's usually meant to be set to a subdirectory of a grandparent, such as D:\User Files\A_L_L\DOWNLOAD_TEMP\artifacts.

    However, the bin and obj subdirectories already go into the project directory by default, so you should be able to run

    dotnet build "D:\User Files\A_L_L\DOWNLOAD_TEMP\test\test.csproj"
    

    which will build D:\User Files\A_L_L\DOWNLOAD_TEMP\test\bin\Debug\net8.0\test.exe. They won't go into your current working directory or anything.