Sysrq147
Sysrq147

Reputation: 1367

What is proper way to define connection string VB

My Visual Basic project uses this connecton string:

Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Admin\Desktop\IzolacCold V2\IzolacCold V2\izolac_cold_dbv2.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True

When I debug it, and go to debug folder, or when I "Release" it then problem occurs. If I run exe file program works normally but it save's data in database defined in connection string and not in database that is created in DEBUG folder (or RELESE folder).

How to properly connect to my databes. How to build proper connection string ?

Upvotes: 1

Views: 276

Answers (1)

Steve
Steve

Reputation: 216303

You should use the DataDirectory substitution string.

For example you could write your connectionstring as

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\izolac_cold_dbv2.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True

In your code then you could control the exact location of the DataDirectory executing this code, BEFORE any attempt to open a connection.

Dim commonDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
Dim myAppDataFolder = Path.Combine(commonDataFolder, "MyAppName")
if Not Directory.Exists(myAppDataFolder) Directory.CreateDirectory(myAppDataFolder)
AppDomain.CurrentDomain.SetData("DataDirectory", myAppDataFolder)

(This example use the C:\programdata\myAppName folder because it is the most appropriate location for read/write data files needed by your application

Your deployment procedure should take care to create the above folder and place the database file in this location.

Upvotes: 2

Related Questions