sql server - error in Connection String in C# -


i new c#. want use microsoft sql server database file test.mdf in output software in c#. in past, had copied connection string in visual studio :

data source=.\sqlexpress;attachdbfilename=c:\users\home\documents\test.mdf;integrated security=true;connect timeout=30;user instance=true 

as see database file path : c:\users\home\documents\test.mdf;

when create setup sofware in visual studio 2008, , install software on pc, errors :

an attempt atach auto-named database file c:\user\home\document\test.mdf failed ...

so want address file installation folder path whith :

string dir = application.startuppath + "\\" + "test.mdf"; 

but when want run program in visual studio 2008 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 field initializer cannot reference 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 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 not match primary file of database. if attempting attach database, retry operation correct files. if existing database, file may corrupted , should restored backup. cannot open user default database. login failed. login failed user 'home-pc\home'.

while have copied right test.mdf file there

as error message says, can't use value of 1 instance field when initializing another. don't want dir field anyway. move of body of constructor... or ideally, create sqlconnection when need anyway. don't use single instance throughout application, go through "create, use, dispose" cycle every time need database access. (ideally, don't in gui code, either...)


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -