Search code examples
c#sqlconnection

Compiler Can't create SqlConnection instance when getting string from file


I have created a Windows Forms application and I am getting data from my database in it, but I have a problem: the SqlConnection object cannot be instantiated.

When I declare this connection string, it works:

static string connectionString = "Data Source=DEVELOPMENT-PC\\SQLEXPRESS;Initial Catalog=DATABASE;Integrated Security=True";

But when I retrieve this from textfile, it doesn't work:

static string a = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]), "connectionString.txt")).ToString();

One point: when I write MessageBox.Show(a);, I see in the window the same string as connection string shown above is.

What could be the problem?


Solution

  • The issue is actually that you have two slashes in the text file. The string is escaped in C# but does not need to be escaped in the text file. The C# is like this:

    "Data Source=DEVELOPMENT-PC\\SQLEXPRESS;Initial Catalog=DATABASE;Integrated Security=True"
    

    Where the text file should just have a single slash:

    Data Source=DEVELOPMENT-PC\SQLEXPRESS;Initial Catalog=DATABASE;Integrated Security=True
    

    This is because you are escaping the slashes in C#, the text file doesn't require escaping the string. For example a string like "This is my\nstring" in C# is two lines, if you want the same effect in a text file you just write it on two lines. The slash is the start of an escape sequence, by writing \ you are telling it to ignore it and use a single slash in its place.

    If you only want a single slash in the C# code, you can do that too:

    static string connectionString = @"Data Source=DEVELOPMENT-PC\SQLEXPRESS;Initial Catalog=DATABASE;Integrated Security=True";
    

    Here the @ symbol tells the compiler that the following string does not contain any escape sequences and to treat it as a literal. This makes it easier especially when working with file paths so you don't have to escape all the slashes.