Access MDF database from executable folder

Asked

Viewed 462 times

3

I am having an annoying problem solving as I want my application to access the database file from the folder where the executable is, because on every computer installed that folder may be on a different drive.

I found that I should use the following code to solve the problem, where supposedly |DataDirectory| refers to a folder in the project’s location, named after App_Data, created the folder, put my database there and used the following code as connection string:

con.ConnectionString = @"Data Source=.\SQLEXPRESS;
                          AttachDbFilename=|DataDirectory|\he_dados.mdf;
                          Integrated Security=True;
                          Connect Timeout=30;
                          User Instance=True";

But this one just doesn’t work, and the system throws me the following exception:

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

Additional information: Falha da instância.

Honestly, I’m getting tired, everything I’m gonna do in C# always has a silly snag in front of me.

  • 1

    You are forcing the file path... It will not work if the file is not exactly here: AttachDbFilename=c:\folder\SampleDatabase.mdf;


  • @Ricardo Oh I’m sorry, that was just an example, I edited the topic and corrected the whole thing.

  • That’s exactly what you did. Put the whole Exception into the question, please?

  • @Ricardo as requested, I put the exception message in the question.

  • Changes your Data Source to (LocalDB)\v11.0 and see if it works.

  • @Ricardo In the first attempt he made the following mistake The user instance flag is not allowed when connecting to a user instance of SQL Server. The connection will be closed. So I removed the User Instance=True, and then it worked. Now, could you explain to me what happened there that it worked? Thanks, you could also put an answer, there is even easier for other people to see, besides having one more answer accepted by you. Thank you

Show 1 more comment

1 answer

4


Recording the solution in the answer:

con.ConnectionString = @"Data Source=(LocalDB)\v11.0;
                          AttachDbFilename=|DataDirectory|\he_dados.mdf;
                          Integrated Security=True;
                          Connect Timeout=30";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.