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…
- 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
-
Proposed as answer by
-
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
-
Edited by
program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
это есть.
public Form1()
{
InitializeComponent();
}
-
Вопрос заданболее трёх лет назад
-
15764 просмотра
В свойствах проекта выставить точку входа
И да, public добавить для класса и для метода Main
Решено, Program.cs как-то вылетел из сборки.
Решение: ПКМ по файлу, включить в сборку.
Пригласить эксперта
-
Показать ещё
Загружается…
09 февр. 2023, в 12:14
1 руб./за проект
09 февр. 2023, в 11:42
7000 руб./за проект
09 февр. 2023, в 11:23
1500 руб./за проект
Минуточку внимания
Hi,
I have a netcoreapp2.0 project that failed to build with the following error when I tried to build it with dotnet build
:
CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Then I open the project in Visual Studio (d15prerel 26629.02), the project built fine in VS, and after that the error is gone from ‘dotnet build’ and it succeeds.
After I run ‘dotnet clean’, ‘dotnet build’ starts failing with the same error
Here is my project file:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.0</TargetFramework> <RuntimeIdentifiers>win10-x64</RuntimeIdentifiers> <!-- omitted AssemblyName and RootNamespace properties --> <LangVersion>Latest</LangVersion> <PackageTargetFallback>$(PackageTargetFallback);portable-net40+sl5+win8+wp8+wpa81;portable-net45+win8+wp8+wpa81</PackageTargetFallback> </PropertyGroup> <ItemGroup> <!-- some project references to other projects --> </ItemGroup> </Project>
There is only one Program.cs file in the project, it has this entry point:
namespace ... { static class Program { ... public static async Task Main(string[] args) { } ...
Cybbber27 0 / 0 / 0 Регистрация: 01.06.2017 Сообщений: 132 |
||||
1 |
||||
22.04.2019, 20:04. Показов 12225. Ответов 21 Метки нет (Все метки)
Здравствуйте, прошу помощи для решения данной ошибки.
Вообще хз что делать, кучу всего перепробовал и те советы которые тут были также испытывал.
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
22.04.2019, 20:04 |
Ответы с готовыми решениями: Программа не содержит статический метод «Main», подходящий для точки входа (CS5001) Программа не содержит статический метод «Main», подходящий для точки входа (CS5001) Программа не содержит статический метод «Main», подходящий для точки входа (CS5001) Как исправить подскажите пожалуйста Программа не содержит статический метод «Main», подходящий для точки входа 21 |
16930 / 12507 / 3286 Регистрация: 17.09.2011 Сообщений: 20,743 |
|
22.04.2019, 20:18 |
2 |
Вообще хз что делать, кучу всего перепробовал А статический метод Main не пробовали где-нибудь создать?
0 |
0 / 0 / 0 Регистрация: 01.06.2017 Сообщений: 132 |
|
22.04.2019, 20:22 [ТС] |
3 |
Да, это первым делом попробовал
0 |
16930 / 12507 / 3286 Регистрация: 17.09.2011 Сообщений: 20,743 |
|
22.04.2019, 20:25 |
4 |
это первым делом попробовал В выложенном коде его нет.
0 |
0 / 0 / 0 Регистрация: 01.06.2017 Сообщений: 132 |
|
22.04.2019, 20:25 [ТС] |
5 |
kolorotur, Потому что он не сработал
0 |
16930 / 12507 / 3286 Регистрация: 17.09.2011 Сообщений: 20,743 |
|
22.04.2019, 20:26 |
6 |
Потому что он не сработал Так и выложенный код тоже не срабатывает Покажите тот, который с Main не сработал.
0 |
0 / 0 / 0 Регистрация: 01.06.2017 Сообщений: 132 |
|
23.04.2019, 10:59 [ТС] |
7 |
kolorotur, Наверное я не правильно созданию этот метод, покажите пожалуйста, пример создания статического метода
0 |
ProgItEasy 454 / 278 / 163 Регистрация: 17.04.2019 Сообщений: 1,603 |
||||
23.04.2019, 11:09 |
8 |
|||
Cybbber27,
1 |
Cybbber27 0 / 0 / 0 Регистрация: 01.06.2017 Сообщений: 132 |
||||
23.04.2019, 11:48 [ТС] |
9 |
|||
ProgItEasy, Не выводит чего-то решение Добавлено через 13 минут
Запускается все, а потом решения на консоль по-просту не выводит
0 |
Usaga 11074 / 7638 / 1178 Регистрация: 21.01.2016 Сообщений: 28,682 |
||||
23.04.2019, 11:56 |
10 |
|||
Запускается все, а потом решения на консоль по-просту не выводит А с чего в консоль что-то должно выводиться? Где подобное в вашем коде?
Строка «какой-то код» это должна за вас сделать?
0 |
0 / 0 / 0 Регистрация: 01.06.2017 Сообщений: 132 |
|
23.04.2019, 12:06 [ТС] |
11 |
Извините за непонимание, это первый код по C#, после Hello World, который мне дали разобрать
0 |
454 / 278 / 163 Регистрация: 17.04.2019 Сообщений: 1,603 |
|
23.04.2019, 12:09 |
12 |
Cybbber27, а где Main? Как раз в Main вы должны делать вызов методов и вывод результатов.
0 |
Cybbber27 0 / 0 / 0 Регистрация: 01.06.2017 Сообщений: 132 |
||||
23.04.2019, 13:01 [ТС] |
13 |
|||
Не знаю, то наверное точно неправильно
Добавлено через 47 минут
0 |
0 / 0 / 0 Регистрация: 01.06.2017 Сообщений: 132 |
|
23.04.2019, 14:22 [ТС] |
14 |
Вот такой результат: Миниатюры
0 |
Andreyip 454 / 333 / 115 Регистрация: 17.08.2014 Сообщений: 1,272 |
||||
23.04.2019, 14:35 |
15 |
|||
Cybbber27,
1 |
0 / 0 / 0 Регистрация: 01.06.2017 Сообщений: 132 |
|
23.04.2019, 14:39 [ТС] |
16 |
Вот Миниатюры
0 |
454 / 333 / 115 Регистрация: 17.08.2014 Сообщений: 1,272 |
|
23.04.2019, 14:57 |
17 |
Cybbber27, уберите статик как с main так и с данного метода. Вам же написаны ошибки.
0 |
0 / 0 / 0 Регистрация: 01.06.2017 Сообщений: 132 |
|
23.04.2019, 15:00 [ТС] |
18 |
Andreyip, Тогда вылезает ошибка — Программа не содержит статический метод «Main», подходящий для точки входа (CS5001)
0 |
454 / 278 / 163 Регистрация: 17.04.2019 Сообщений: 1,603 |
|
23.04.2019, 15:19 |
19 |
Cybbber27, есть файл, откуда данные считываются?
0 |
0 / 0 / 0 Регистрация: 01.06.2017 Сообщений: 132 |
|
23.04.2019, 16:14 [ТС] |
20 |
ProgItEasy,Я понимаю, что в главном методе я должен вызвать решение и оно выйдет на консоль Добавлено через 24 секунды Добавлено через 49 минут
0 |
If you want to create an executable file from your ‘C#’ project or file, your code should contain a ‘static Main’ method. This is an entry point to ‘C#’ program. Otherwise, ‘C#’ compiler will throw the below error:
error CS5001: Program 'xyz.exe' does not contain a static 'Main' method suitable for an entry point
To resolve this error, we have two options here.
- One is, add ‘
static Main
‘ method into the project or the class.- Entry point for standalone ‘C#’ application is it’s ‘Main’ method. ‘
static Main
‘ method should exist in any one class in ‘C#’ project or file.
- Entry point for standalone ‘C#’ application is it’s ‘Main’ method. ‘
- Other option is, build the project or file as a library (DLL – Dynamic Link Library).
- These type of files are not self-executable. DLL files will be used into other assemblies or applications. So, for these file, ‘Main’ entry point is not required.
That said, depending on the requirement, we can create a self executable file or a DLL from the ‘C#’ code file or project.
Let’s take a simple example to produce the error and discuss about the steps to resolve the issue.
// Sample.cs public class Sample { public void Display() { System.Console.WriteLine("Hello, World!"); } };
When we compile above program; ‘C#’ compiler will throw below error:
c:>csc Sample.cs Microsoft (R) Visual C# Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 Copyright (C) Microsoft Corporation. All rights reserved. error CS5001: Program 'c:Sample.exe' does not contain a static 'Main' method suitable for an entry point
As we mentioned above, we have two ways to resolve this problem. Lets try to resolve this without modifying any code.
Compile the above program “Sample.cs” as a target library instead of an executable. Below is the command:
c:>csc /target:library Sample.cs Microsoft (R) Visual C# Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 Copyright (C) Microsoft Corporation. All rights reserved. Observe that 'C#' compiler successfully compiled the program and generates "Sample.dll" file.
Another way to resolve this error is, by adding the ‘static Main’ method. ‘Main’ method should be added into the ‘Sample’ class as a static method. After adding the ‘Main’ method above code looks like below.
// Sample.cs public class Sample { public void Display() { System.Console.WriteLine("Hello, World!"); } static void Main() { } };
Now compile this program and observe that ‘C#’ compiler successfully compiled the program and generates “Sample.exe” file. Below is the command to compile above code:
csc basic.cs
We can choose any one of these methods, depending on our requirements, to resolve this issue “error CS5001”.
(Raju)
Я новичок в C #. Я был бы благодарен, если бы кто-нибудь мог показать мне, почему для кода отображается следующая ошибка.
«Программа CS5001 не содержит статического метода Main, подходящего для точки входа»
using System;
class test
{
void Foo(int x) { Console.WriteLine(x); }
void Foo(double x) { Console.WriteLine(x); }
void Foo(int x, float y) { Console.WriteLine(x); Console.WriteLine(y);}
void Foo(float x, int y) { Console.WriteLine(x); Console.WriteLine(y); }
void Main()
{
Foo(123); // int
Foo(123.0); // double
Foo(123, 123F); // int, float
Foo(123F, 123); // float, int
}
}
2 ответа
Лучший ответ
Ваш фиксированный код должен выглядеть так:
using System;
class test
{
static void Foo(int x) { Console.WriteLine(x); }
static void Foo(double x) { Console.WriteLine(x); }
static void Foo(int x, float y) { Console.WriteLine(x); Console.WriteLine(y); }
static void Foo(float x, int y) { Console.WriteLine(x); Console.WriteLine(y); }
static void Main()
{
Foo(123); // int
Foo(123.0); // double
Foo(123, 123F); // int, float
Foo(123F, 123); // float, int
}
}
1
Daniel
3 Ноя 2016 в 04:17
Эта ошибка возникает, когда метод Main
определен с неправильной подписью. Эта ошибка также возникает, если Main
определен с неправильным регистром, например, в нижнем регистре main.
Main должен быть объявлен как статический, и он должен возвращать void или int, и он должен либо не иметь параметров, либо иметь один параметр типа string []
Определите свой основной метод следующим образом —
static void Main()
ИЛИ вот так —
static void Main(string[] args)
Дополнительную информацию можно найти по этой ссылке.
4
Yogi
3 Ноя 2016 в 05:16