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.
You are forcing the file path... It will not work if the file is not exactly here:
AttachDbFilename=c:\folder\SampleDatabase.mdf;

– Ricardo
@Ricardo Oh I’m sorry, that was just an example, I edited the topic and corrected the whole thing.
– Ezequiel Barbosa
That’s exactly what you did. Put the whole Exception into the question, please?
– Ricardo
@Ricardo as requested, I put the exception message in the question.
– Ezequiel Barbosa
Changes your Data Source to
(LocalDB)\v11.0
and see if it works.– Ricardo
@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 theUser 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– Ezequiel Barbosa