Read AppSettings value from text file (Notepad) using C# and VB.Net in Windows Application

Last Reply one year ago By pandeyism

Posted one year ago

app config file code as follows

    <add key="ConStringprod" value="E:\Timesheet\Timesheet\bin\Debug\Prodcon.txt"/>

CSharp code as follows

string ConStringprod = ConfigurationManager.AppSettings["ConStringprod"].ToString();
SqlCommand cmd = null;
SqlDataAdapter da = new SqlDataAdapter("Select * from user",ConStringprod);

when i run the code i get error as follows

An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll

i want to read the connection string from Prodcon text file using c#

The above error shows in below line  

SqlDataAdapter da = new SqlDataAdapter("Select * from user",ConStringprod);

how to solve this error

Posted one year ago Modified on one year ago

Hey narasiman,

Please refer below sample.



using System.Configuration;
using System.IO;
using System.Data.SqlClient;


Imports System.Configuration
Imports System.IO
Imports System.Data.SqlClient



private void Form1_Load(object sender, EventArgs e)
    string path = ConfigurationManager.AppSettings["constr"].ToString();
    string constr = File.ReadAllText(path);
    using (SqlConnection con = new SqlConnection(constr))
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                DataTable dt = new DataTable();
                dataGridView1.DataSource = dt;


Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim path As String = ConfigurationManager.AppSettings("constr").ToString()
    Dim constr As String = File.ReadAllText(path)
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand("SELECT * FROM Customers", con)
            Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
                Dim dt As DataTable = New DataTable()
                dataGridView1.DataSource = dt
            End Using
        End Using
    End Using
End Sub