Susan Tony
Susan Tony

Reputation: 11

System invalid operator error when connecting to a SQL Server database

Here's my program. I am new to c#, also programming. I am getting an error while running this program. What I am trying to do here is load the connection string from App.config, then connect to the database, read from a datatable and export a few columns to Excel as .csv:

class Program
{       
    public static string ConnectionString = ConfigurationManager.AppSettings["DbSource"];

    static void Main(string[] args)
    { 
        GetCpudata();  
    }

    //Export to csv ORACLE Test CPU Data
    public static void GetCpudata()
    {
        StringBuilder sb = new StringBuilder();

        using (SqlConnection con1 = new SqlConnection(ConnectionString))
        {       
            con1.Open();   ////ERROR HERE
            Console.WriteLine("Opening db");

            SqlDataAdapter da = new SqlDataAdapter(" select * from ComplianceComputer_MT", con1);
            DataSet sourcedata = new DataSet();
            da.Fill(sourcedata);
            sourcedata.Tables[0].TableName = "Test";

            foreach (DataRow row in sourcedata.Tables["Test"].Rows)
            {
                sb.Append(row["ComputerName"].ToString()); 
                sb.Append(row["[MaxClockSpeed]"].ToString()); 
                sb.Append(row["[Manufacturer]"].ToString()); 
                sb.Append(row["[ModelNo]"].ToString()); 
                sb.Append(row["[NumberOfCores]"].ToString()); 
                sb.Append("\r\n");
            }
        }

        StreamWriter file = new StreamWriter(@"C:\StudyC\TestData\Exported Data\Test.csv");
        file.WriteLine(sb.ToString());
        file.Close();
    }
}

Dbsource in App.config.

My App Config settings:

<connectionStrings>
    <add name="DbSource" connectionString="Data Source=192.168.10.109\SAMPLE;Initial Catalog=FlexNet;Integrated Security=True;User ID=test;Password=test;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
</connectionStrings>

Also, I want a few more columns in excel that need to be filled in as null when no corresponding columns are available in the database table.

Any idea on how to achieve this?

Upvotes: 1

Views: 197

Answers (1)

Cory
Cory

Reputation: 793

This should get you the correct connection string:

public static string ConnectionString = ConfigurationManager.ConnectionStrings["DbSource"].ConnectionString;

Upvotes: 1

Related Questions