Possible Duplicate:
SQL Express Connection string - Relative to application location
I have a desktop application written in vb.net. The app uses an SQL Server express 2008 database (.mdf file). Currently i have the connection string as absolute path like this:
Dim ObjConnection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Pantheo\Documents\Visual Studio 2010\Projects\Food Manager 2012(new)\Food Manager 2012\Food_CustomerDB.mdf;Integrated Security=True;User Instance=True")
At my pc it runs just great. If i build it though and get the .exe to run to a defferent pc it crashes because it cannot attach the database.
I have tried to make it relative using this connection string:
Dim ObjConnection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Food_CustomerDB.mdf;Initial Catalog=Food_CustomerDB;Integrated Security=True;User Instance=True")
with no success. Can someone help me? I know there are a ton other answers for it, basically regarding C#, but i cannot implement them. Thanks in advance
The DataDirectory
value is just a string extracted from the AppDomain.CurrentDomain property list. In a WinForm application is not pre-defined but you could set it before opening your database.
AppDomain.CurrentDomain.SetData("DataDirectory", @"C:\MyReadWriteFolder")
then the connection string with AttachDbFilename=|DataDirectory|\Food_CustomerDB.mdf
should works provided you put the database there (C:\MyReadWriteFolder).