-1

I'm trying to make it so I can use the program where ever I put the folder so it's not just restricted to be in one specific place. This is the connection string i'm using right now

string constring = "Data Source = (LocalDB)\\MSSQLLocalDB;
AttachDbFilename = C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf; 
Integrated Security = True";

This connection string works fine and all but as said above I want it to be environmental to where I put it

Nico Zhu
  • 32,367
  • 2
  • 15
  • 36

4 Answers4

0

You can provide variables to values such as data source, attachDbFilename, etc. Then retrieve values at the loading event. Or use config file to retrieve connection string. As in first solution appear like this

string constring = "Data Source = "+ YourDataSource +"; AttachDbFilename = "+ YourAttachedDBFilePath +"; Integrated Security = True";
PNP
  • 361
  • 5
  • 17
  • How do i retrive the values at loading? – h. Corbett Oct 19 '17 at 09:05
  • which type of project you are creating? Its differ according to project type. Most of the time database connection string define in app.config file in windows applications and web.config file in web applications – PNP Oct 19 '17 at 11:25
0

You should put database file inside folder app (debug or release) and call it by Application.StartupPath

PNP
  • 361
  • 5
  • 17
khanh2990
  • 1
  • 2
0

If it is possible, then put the needed database into the AppData folder and then use the following in the ConnectionString

Server=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|BarcodeDB.mdf;Database=BarcodeDB;

If not, then the best way to do it to use the option that proposed Promod, but in that case, you have to know the exact place of the database in every single environment, or do the search in every environment to find necessary DB.

mustf4
  • 105
  • 3
0

If you want to find the path for your project you can use:

string path = System.AppDomain.CurrentDomain.BaseDirectory;

An alternative, if you decide to store the db file in the build folders (next to your executable):

string path = Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);

Example:

// filename of your Db file
string filename = "BarcodeDB.mdf";
// combine filename and your local path
string dbFilePath = Path.Combine(path, filename);
// use the db filepath in your constring using string interpolation
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = {dbFilePath}; Integrated Security = True";

So when you move your project or have it on various machines (assuming the db file is present), it should be able to find it.

Cicero
  • 2,872
  • 3
  • 21
  • 31