0

Here is my connection string:

SqlConnection myConnection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\m_bou\Desktop\PCOTools\Numbers.mdf;Integrated Security=True;Connect Timeout=10");

I have tried using the |DataDirectory|\Numbers.mdf, and also many other options people have tried but no luck! I just want it to load the mdf file that is in the executable directory when it loads... in my case its the debug folder, but when I deploy on a different machine it needs to be wherever the exe resides. Can anyone tell me what i'm doing wrong? This is a Winform applicagtion...

Joel Christophel
  • 2,604
  • 4
  • 30
  • 49
  • While not the best option possible the |DataDirectory| should work fine if you keep present some caveats. What error did you get with DataDirectory? – Steve Jun 07 '16 at 21:38
  • What kind of project is this in? If it is a class library then DataDirectory doesn't actually exist. You have to define it in your Main(). Something like this: `AppDomain.CurrentDomain.SetData("DataDirectory", AppDomain.CurrentDomain.BaseDirectory);` Another helpful answer? http://stackoverflow.com/questions/12187068/where-is-datadirectory-defined – mikesigs Jun 07 '16 at 21:40
  • For Web applications, AttachDbFilename=|DataDirectory|Numbers.mdf would point to the App_Data folder of your project, but I don't know for Winform applications. – kimbaudi Jun 07 '16 at 22:27
  • I don't get an error. What happens is it changes the database to the default database settings that I get when first creating it, and then gives me the error that it can't find the table anymore. If I use the server explorer in Visual studio it shows me that indeed the db has changed, so I remove it, replace with a backup mdf of the db and all is well, as long as I set an absolute path to the mdf file. – Mike Boutin Jun 08 '16 at 12:34
  • Mike, I also tried your approach with no luck – Mike Boutin Jun 08 '16 at 12:48
  • This is the error I get: An attempt to attach an auto-named database for file C:\Users\m_bou\Documents\Visual Studio 2015\Projects\PCO Tools\PCO Tools\bin\Debug\Numbers.s3db failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. Here is connection string: AppDomain.CurrentDomain.SetData("DataDirectory", AppDomain.CurrentDomain.BaseDirectory); myConnection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Numbers.s3db;Integrated Security=True;Connect Timeout=10"); – Mike Boutin Jun 08 '16 at 20:03
  • I got it working now... not sure why it didnt work before. I switch to a sqlite DB and the following connection string works as expected... myConnection = new SQLiteConnection(@"Data Source=|DataDirectory|\Numbers.sqlite; Version=3"); – Mike Boutin Jun 08 '16 at 21:54

0 Answers0