Ошибка компилятора cs5001

Permalink

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error CS5001

Compiler Error CS5001

08/27/2018

CS5001

CS5001

e1e26e75-84e0-47c7-be8a-3c4fd0d6f497

Compiler Error CS5001

Program does not contain a static ‘Main’ method suitable for an entry point

This error occurs when no static Main method with a correct signature is found in the code that produces an executable file. It also occurs if the entry point function, Main, is defined with the wrong case, such as lower-case main. For information about the rules that apply to the Main method, see Main() and Command-Line Arguments.

If the Main method has an async modifier, make sure that the selected C# language version is 7.1 or higher and to use Task or Task<int> as the return type.

The Main method is only required when compiling an executable file, that is, when the exe or winexe element of the TargetType compiler option is specified. The following Visual Studio project types specify one of these options by default:

  • Console application
  • ASP.NET Core application
  • WPF application
  • Windows Forms application

Example

The following example generates CS5001:

// CS5001.cs
// CS5001 expected when compiled with -target:exe or -target:winexe
public class Program
{
   // Uncomment the following line to resolve.
   // static void Main() {}
}

I got this error when using the command Build Docker Image in Visual Studio 2022.

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

The project built perfectly well in Windows but I tried to build a Linuxcontainer. Switching to Output Type Class Library solved the error but Docker Compose gave me this error instead:

CTC1031 Linux containers are not supported for

https://stackoverflow.com/a/74044317/3850405

I tried explicitly using a Main method like this but it did not work:

namespace WebApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {

I have no idea why but this solved it for me:

Gives error:

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["src/Services/Classification/ClassificationService.Api/ClassificationService.Api.csproj", "Services/Classification/ClassificationService.Api/"]

RUN dotnet restore "Services/Classification/ClassificationService.Api/ClassificationService.Api.csproj"
COPY . .
WORKDIR "/src/Services/Classification/ClassificationService.Api"
RUN dotnet build "ClassificationService.Api.csproj" -c Release -o /app/build

Works:

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["src/Services/Classification/ClassificationService.Api/ClassificationService.Api.csproj", "src/Services/Classification/ClassificationService.Api/"]

RUN dotnet restore "src/Services/Classification/ClassificationService.Api/ClassificationService.Api.csproj"
COPY . .
WORKDIR "/src/src/Services/Classification/ClassificationService.Api"
RUN dotnet build "ClassificationService.Api.csproj" -c Release -o /app/build

Notice the double /src in the working example.

I read that you had to place the Dockerfile at the same level as .sln file but in my case the files are separated by four levels.

https://stackoverflow.com/a/63257667/3850405

As OP did not restricted to WinForms, and I have this error because of a mixed WinForms => WPF approach, I feel that is OK to answer here.

In my case I have .NET Framework 4.8 that gets data from an ancient Outlook .pst file; on top of this I want to display contacts with a WPF UI — I know, I know, why not with a WinForms?

For WPF, I had to add System.Xaml, PresentationCore and PresentationFramework and of course deleted the Form1.cs and Program.cs causing the error msg «CS5001 Program does not contain a static ‘Main’ method suitable for an entry point» that immediately appeared.

After some SO Googling, I came here and to another thread and came up with this change at .csproj:

  <ItemGroup>
    <!--<Page Include="App.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </Page>-->
    <!-- ^^^^^^^^ ERROR ^^^^^^^^ -->
    <!-- Above leads to an error Message "CS5001 Program does not contain a static 'Main' method suitable for an entry point"-->
    
    <!-- Below is the fix for WPF in NET Framework --> 
    <ApplicationDefinition Include="App.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </ApplicationDefinition>
    ...
  <ItemGroup>

PS: As a side note, when you unload the project and click Edit Project File and ask for Find App.Xaml with CTRL-F do you notice that — sometimes, at least — the default scope is Current Project? And as your Project is unloaded, although you are in the .csproj it does not find anything inside the current .csproj?

I lose a lot of minutes in that :( before I realize that I had to change scope to Current Document

Elfman99

1 / 1 / 0

Регистрация: 15.02.2017

Сообщений: 102

1

25.12.2018, 18:22. Показов 8789. Ответов 5

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;
 
namespace First
{
    class Unit2
    {
        public void Input()
        {
            string begin_dir;
            string end_dir;
            Console.WriteLine("Введите путь копируемого каталога");
            begin_dir = Console.ReadLine();
            Console.WriteLine("Введите путь куда копировать каталог");
            end_dir = Console.ReadLine();
            Copy(begin_dir, end_dir);
        }
        public void Copy(string begin_dir, string end_dir)
        {
            DirectoryInfo dir_inf = new DirectoryInfo(begin_dir);
            foreach (DirectoryInfo dir in dir_inf.GetDirectories())
            {
                if (Directory.Exists(end_dir + "\" + dir.Name) != true)
                {
                    Directory.CreateDirectory(end_dir + "\" + dir.Name);
                }
                Copy(dir.FullName, end_dir + "\" + dir.Name);
                Thread.Sleep(100);
            }
            foreach (string file in Directory.GetFiles(begin_dir))
            {
                string filik = file.Substring(file.LastIndexOf('\'), file.Length - file.LastIndexOf('\'));
                File.Copy(file, end_dir + "\" + filik, true);
                Thread.Sleep(100);
            }
        }
 
        public void pro2()
        {
            string begin_dir = "E:\Новая папка";
            string end_dir = "E:\Новая папка";
            pro(begin_dir, end_dir);
 
        }
 
        public void pro(string begin_dir, string end_dir)
        {
            DirectoryInfo dir_inf = new DirectoryInfo(begin_dir);
            List<string> name = new List<string>();
            foreach (DirectoryInfo dir in dir_inf.GetDirectories())
            {
                name.Add(dir.Name);
                pro(dir.FullName, begin_dir + "\" + dir.Name);
            }
            foreach (string dir in Directory.GetFiles(begin_dir))
            {
 
                string filik = dir.Substring(dir.LastIndexOf('\'), dir.Length - dir.LastIndexOf('\'));
                name.Add(filik);
            }
            foreach (string p in name)
            {
                Console.WriteLine(p);
            }
        }
    }
}



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

25.12.2018, 18:22

5

dazering

92 / 62 / 31

Регистрация: 22.12.2018

Сообщений: 121

25.12.2018, 20:03

2

Лучший ответ Сообщение было отмечено Elfman99 как решение

Решение

А где точка входа?

C#
1
2
3
static void Main(){
*Ваши методы*
}

Решение: добавить метод выше написанный или там где он есть

C#
1
using First;



0



1 / 1 / 0

Регистрация: 15.02.2017

Сообщений: 102

25.12.2018, 20:06

 [ТС]

3

То есть using «namespace» после statoc void Main() писать?



1



92 / 62 / 31

Регистрация: 22.12.2018

Сообщений: 121

25.12.2018, 20:10

4

Лучший ответ Сообщение было отмечено Elfman99 как решение

Решение

Желательно в самом верху.

Цитата
Сообщение от Elfman99
Посмотреть сообщение

using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;

Например в вашем коде все using относятся к

Цитата
Сообщение от Elfman99
Посмотреть сообщение

namespace First
{

Иными словами перед первыми скобками



0



1 / 1 / 0

Регистрация: 15.02.2017

Сообщений: 102

25.12.2018, 20:25

 [ТС]

5

Ошибка CS5001 Программа не содержит статический метод «Main» для Backup

теперь на copy орет, требует ссылку на объект



0



dazering

92 / 62 / 31

Регистрация: 22.12.2018

Сообщений: 121

25.12.2018, 20:48

6

Лучший ответ Сообщение было отмечено Elfman99 как решение

Решение

Этот метод для объекта. Добавьте к сигнатуре метода static

C#
1
public static void Copy(...)



0



  • Remove From My Forums
  • Question

  • Hello,

    I added yesterday a class and added some code from a website. Later on I want it to remove it from the solution so what I did is started VS and remove it from the solution. Since then I received this error when I want to start and test the Windows Form Application.
     

    So what I did is Google around but I found nothing what results into the solution. I checked every form for in any case something that’s looks like a Main. So what I found on the top in every form was:

    public (form name)()
            {
                InitializeComponent();
            }

    I’m afraid that I’ve done something wrong, but I don’t know what. So the title is what I see when the program itself is starting to build it. The error list says: Program does not contain a static ‘Main’ method suitable for an entry point. I see only
    a red cross. No error code. But the file is CSC, so what is that?

    So I was hoping that someone could help me so that I could test/build the solution again. Thanks anyway!

    Donovan

Answers

  • Did you accidentally remove the entire program.cs file?

    If you create a new Windows Forms application you will see that you should have a Program.cs file containing a static class called Program with a static method called Main (and a comment saying this is the main entry point for the application).

    • Proposed as answer by

      Thursday, June 16, 2016 4:46 PM

    • Marked as answer by
      DotNet Wang
      Tuesday, June 28, 2016 1:54 AM

  • Hi Donovan_DD,

    >>”So could I just copy and paste the code at a new window form witch I should add to the solution”

    You could right click and add a new class named “Program.cs” and add below code in it to solve your problem. In the code, you should modify the parameter
    value of “Application.Run()” and make it as the first start form class.

    Or, you could create a new clean windows form application and then copy it “Program.cs” file to your project. Then, modify the namespace and first start
    form according to your need.

    namespace WindowsFormsApplication1
    {
        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new TheFirstStartForm());
            }
        }
    }

    Best Regards,

    Albert Zhang

    • Edited by
      Albert_Zhang
      Saturday, June 25, 2016 4:58 AM
    • Marked as answer by
      DotNet Wang
      Tuesday, June 28, 2016 1:54 AM

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора cs1503
  • Ошибка компилятора cs1061
  • Ошибка компилятора cs0426
  • Ошибка компилятора cs0266
  • Ошибка компилятора cs0236