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

Last Reply 11 months ago By pandeyism

Posted 11 months ago

app config file code as follows

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

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 11 months ago Modified on 11 months ago

Hey narasiman,

Please refer below sample.

Namespaces

C#

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

VB.Net

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

Code

C#

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();
                da.Fill(dt);
                dataGridView1.DataSource = dt;
            }
        }
    }
}

VB.Net

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()
                da.Fill(dt)
                dataGridView1.DataSource = dt
            End Using
        End Using
    End Using
End Sub

Screenshot