'VB.Net ConnectionString with a local .mdf database

I am publishing a project application and I think having a connectionstring with this format

cn.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\iaprubillos\My Documents\PROJECT\myProject\database\myDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"

is not a friendly and definitely won't work when I will run the application on other computers. Question: Can I use a connectionstring in a format of

cn.ConnectionString = "Data Source=|DataDirectory|\myDatabase.mdf"

and store the database in bin folder so that when I Build my project and compile to an .exe file, the .exe file can still access the database?



Solution 1:[1]

You can use My.Application.Info.DirectoryPath to get the path where your application is running from. So you can modify your connextion string code like this:

cn.ConnectionString = String.format("Data Source=.\SQLEXPRESS;AttachDbFilename={0}\myDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True", My.Application.Info.DirectoryPath)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt Wilko