LesterNotTheMolestor
LesterNotTheMolestor

Reputation: 141

Reading the connection string from an external file

I'm rather new both to C# and SQL. I am trying to read the connection string from an external .text file when the program loads, and then use it as a variable whenever I need it in the code, however I'm getting an error I have never seen before. What could be going wrong?

The connection string is this:

@"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd";

And the code I am using to transform that into a string is this:

    private void Form1_Load_1(object sender, EventArgs e)
    {

        string connectionString;
        var path = @"C:\Users\Administrator\Desktop\connstring.txt";
        using (StreamReader sr = new StreamReader(path))
        {
            connectionString = sr.ReadLine();
        }

        var connection = new SqlConnection(connectionString);


        SqlConnection conn = connection;

However, as I mentioned I'm getting this error:

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

Additional information: Keyword not supported: '@"data source'.

Upvotes: 2

Views: 1941

Answers (1)

Thomas Stringer
Thomas Stringer

Reputation: 5862

Take the @ symbol and the double quotes out of your text file. Those aren't needed.

Your text file should read:

Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd;

Important note

You shouldn't be storing your user credentials (especially for sa!!) as plain text in a file.

Upvotes: 2

Related Questions