eirishainjel
eirishainjel

Reputation: 600

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?

Upvotes: 1

Views: 9913

Answers (1)

Matt Wilko
Matt Wilko

Reputation: 27342

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)

Upvotes: 0

Related Questions