0

I am accessing a service based database by using the following connection string

static string appath = Library_Records.Program.app_path;

string connectionstring = @"Data Source=.\SQLEXPRESS;AttachDbFilename=appath;Integrated Security = true;User Instance = True";
connection = new SqlConnection(connectionstring);

 static string dbfiles = null;
 internal static string app_path
 {
     get { return dbfiles = "|Datadirectory|\\5700.mdf"; }
 }

Library_Records:namespace, Program is the class name containing Main()

When I call connection.Open(), it gives the following error

An attempt to attach an auto-named database for file appath failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

5700 is my database with .mdf extension. How to rectify this problem?

1 Answer 1

3

Variables are never automatically replaced with values in strings, so AttachDbFilename=appath; will not work.

You should do something like:

string connectionstring = 
    string.Format(@"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;User Instance=True", appath);

connection = new SqlConnection(connectionstring);
Sign up to request clarification or add additional context in comments.

2 Comments

It worked thankyou sir Now if i create a setup file(.exe) then will the database be accessible on any other computer because i first created a setup in which AttachDbFilename=C:\Users\Sarao\Documents\prjs\Library_Records\Library_Records\5700.mdf and when i run it on the other computer it said that database is not accessible followed by path
As long as you copy your database file to another computer together with your program - it should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.