0

Can someone help me out?

Whenever I switch computers I have to copy the connection string again. I don't want to do that. Is there any alternative method for finding it? I am using Visual Studio 2013 and C#.

I have kept the application in a flash drive so I may use it on any computer. But it only works on my computer.

con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=H:\DataBaseApp\DataBaseApp\DB.mdf;Integrated Security=True"); 
con.Open();

This is what I'm using but I would appreciate if someone tells me how not to use this.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • Does your flash drive always get mounted as the `H:` drive on all the computers you're using this on? – marc_s Sep 12 '14 at 20:46

2 Answers2

0

1) Create connection string property

2) Add connection string to web config. DataSource should be some alias like TestDataBase.

3) Fill the connection string property from web config value.

4) Add Sql Alias on the current PC with name TestDataBase.

When you go to another PC you should only configure new SQL Alias.

In this case multiple users can work without changes in the code(Example source control).

mybirthname
  • 17,949
  • 3
  • 31
  • 55
0

You can save your connection string in any text file, for example: conn.txt and put it in bin\Debug folder. Now, you can read it at runtime by using this code.

string path = Path.Combine(Application.StartupPath, "conn.txt");
string connStrg = System.IO.File.ReadAllText(path);
using (SqlConnection cnn = new SqlConnection(connStrg))
{
    ...
}

When you publish your application you need to just create that file where the application is installed. I mean if your application is installed in any specific drive like D:\\MyFolder\\MyApp.exe then your conn.txt file should be created on D:\\MyFolder.

Shell
  • 6,818
  • 11
  • 39
  • 70
  • but when i will change pc path will also change and again i have to copy the connection string. – Najam Sahar Oct 14 '14 at 14:05
  • i want to get the connection string automatically – Najam Sahar Oct 14 '14 at 14:05
  • hmm.. In that case you need to find out the available sql server. if there're more than one than you need to select only one. You can check this [answer](http://stackoverflow.com/a/10781356/3761928) to know how to find out the available sql server. Dynamic connection may have different id-password for sql authentication. So, you have to connect the database using Windows Authentication and also it may not possible to connect server without creating named pipe if you are trying to connect network server. – Shell Oct 15 '14 at 03:24