SoheilYou
SoheilYou

Reputation: 949

error in Connection String in C#

I am new to C#. I want to use my Microsoft SQL Server database file test.mdf in my output software in C#. In the past, I had just copied the connection string in Visual Studio like this :

Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Home\Documents\test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True

as you see the database file path is : C:\Users\Home\Documents\test.mdf;

When I create setup for my sofware in Visual Studio 2008, and install the software on another PC, it errors :

An attempt to atach an auto-named database for file C:\User\Home\Document\test.mdf failed ...

So I want to address the file with the installation folder path whith this :

string dir = Application.StartupPath + "\\" + "test.mdf";

but when I want to run program in Visual Studio 2008 it erros

string dir = Application.StartupPath + "\\" + "test.mdf";
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=" + dir + ";Integrated Security=True;Connect Timeout=30;User Instance=True");

Error 1 A field initializer cannot reference the non-static field, method, or property 'phonebook.Form1.dir' C:\Users\Home\Documents\Visual Studio 2008\Projects\phonebook\phonebook\Form1.cs 25 95 phonebook

UPDATE

When I use

 SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename="+ Application.StartupPath +" \\test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");

it errors :

One or more files do not match the primary file of the database. If you are attempting to attach a database, retry the operation with the correct files. If this is an existing database, the file may be corrupted and should be restored from a backup. Cannot open user default database. Login failed. Login failed for user 'Home-PC\Home'.

While I have copied right test.mdf file there

Upvotes: 1

Views: 2685

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499780

As the error message says, you can't use the value of one instance field when initializing another. You probably don't want dir as a field anyway. Just move all of this into the body of the constructor... or ideally, only create your SqlConnection when you need it anyway. Don't use a single instance throughout your application, but go through a "create, use, dispose" cycle every time you need database access. (Ideally, don't do this in your GUI code, either...)

Upvotes: 3

Related Questions