1

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

Community
  • 1
  • 1
Pantheo
  • 129
  • 1
  • 8
  • 15
  • http://stackoverflow.com/questions/3500829/sql-express-connection-string-relative-to-application-location is probably what you want, there is very little code there that wouldnt translate easily to vb – Daniel Powell Jun 05 '12 at 06:30

1 Answers1

1

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).

Steve
  • 213,761
  • 22
  • 232
  • 286
  • And how do i put the database there in an aother machine? With an installer mabey? – Pantheo Jun 05 '12 at 08:38
  • Of course, you need an installer tool, start with the deplyment project on Visual Studio, or use one of the many free or paid tools available. Remeber also that SQL Server need to be installed on the customer PC. Or, if your program is intended for a single user you could use the [LocalDB](http://stackoverflow.com/questions/9655362/localdb-deployment-on-client-pc) version of SqlServer – Steve Jun 05 '12 at 08:59
  • Steve i cant seems to figure that out. Can you please be more specific? I would write the above to my form_load? I will look it again fresh in the morning. If you could help me some more i would appreciate it! – Pantheo Jun 05 '12 at 21:40
  • I found a temporary solution. I did what you said and worked without installation as long as i have my flash hard drive on. Thanks for your help Steve! – Pantheo Jun 06 '12 at 06:58