An unhandled exception of type 'System.NullReferenceException' occurred in Lesson1.exe
Additional information: The object reference does not indicate an object instance.

Why do I get this exception?

Code example:

static void Main(string[] args) { var context = new TestDataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); var roles = context.Roles.ToList(); foreach (var role in roles) { Console.WriteLine("{0} {1}", role.Code, role.Name); } Console.ReadLine(); } 

The exception crashes in this place:

 TestDataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); 

example app.conf :

 <connectionStrings> <add name="ConnectionString" connectionString="Data Source=WEBBD\test;Initial Catalog=Web;User ID=test;Password=1234" providerName="System.Data.SqlClient" /> </connectionStrings> 

I will show clearly what is happening, and that I can not enter image description here enter image description here enter image description here What did I do wrong?

  • Where did you get the app.conf file? - Pavel Mayorov

1 answer 1

The immediate reason for the exception is ConfigurationManager.ConnectionStrings["ConnectionString"] returned null. This means that the connection string with the specified name was not found.


And she was not found that's why.

The handler of the ConfigurationManager.ConnectionStrings section works with the main configuration file of your application, which has the name "{имя вашего главного модуля}.exe.config" and which is generated during the build based on the app.config file in your project.

If you have named your app.conf file, it cannot be accessed through the simplified configuration API.

  • Above attached screenshots of the project and what does not work, thanks for the answer and help - Ethernets
  • @Ethernets you have two files with the same name ... Do you want to talk further or yourself? - Pavel Mayorov
  • Yes, if possible, I renamed 1 App.config file to te.config which is in Consoles, and nothing has changed. I also get an exception, or are we talking about different files ?? - Ethernets
  • @Ethernets you did something stupid, try something else - Pavel Mayorov
  • Excuse me, please, and what about file? I just don’t see name matches, thanks - Ethernets