C# console application Invalid Operation Exception

mnlfischer picture mnlfischer · Mar 22, 2013 · Viewed 61.6k times · Source
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;

namespace BissUpdater
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "Data Source=H....; 
                Initial Catalog=LANDesk; Persist Security Info=True; 
                User ID=Mainstc; Password=xxxxxxxx";

            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
        }
    }
}

The SQL Connection threw a invalid operation exception.

"Invalid Operation. The connection is closed".

This is my complete Code. In a other program, it works perfect.

That is the second time, that doesnt work. Im working with VS2005...maybe my program is damaged?

Stacktrace:

at System.Data.SqlClient.SqlConnection.GetOpenConnection()
at System.Data.SqlClient.SqlConnection.get_ServerVersion()

Answer

BizApps picture BizApps · Mar 22, 2013

The correct way doing that should be something like:

static void Main(string[] args) {
    string connectionString = "Data Source=H....; 
    Initial Catalog=LANDesk;User ID=Mainstc; Password=xxxxxxxx"; 
    // removed Persist Security Info=True; 


    using(SqlConnection con = new SqlConnection(connectionString))
    {
      if (con.State==ConnectionState.Closed)
      {                      
          con.Open();   
      }
    }


}

Using Using Statement it will automatically dispose your SQL connection.

Check this also: Best Practices for Using ADO.NET on MSDN

Other things to do: Use SQL Management Studio and try to use your sql authentication login credential from your connection string and if you have successfully connected to your database using that account the above code should work for you.

Best Regards