0

I have a connection string set in my App.Config

<add name="project.Database.Database"
     connectionString  = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Desktop\Project\Database\Database.mdf;Integrated Security=True"
providerName = "System.Data.SqlClient" />

I access the database like this:

 private static string ConnectionString = ConfigurationManager.ConnectionStrings["Database.Database.sfd"].ConnectionString;

    //Open the connection and check if the reader has found any rows of data.
 using (this.SqlCon = new SqlConnection(ConnectionString))
 using (SqlCommand cmd = new SqlCommand(query, SqlCon))
 {//blahh}

it works perfectly however, when i use it on another PC etc it doesnt work as i have hard coded the connection string to a certain location.

How can i make it so that at startup the connection string is set to the current location of the database.

Thanks all

Jignasha Royala
  • 1,032
  • 10
  • 27
  • Use the Environment.SplecialFolder.CommonApplicationData and install your db in the location pointed by that enum – Steve Apr 12 '18 at 14:34
  • 1
    You could also use a [relative path instead of a fully qualified one](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#fully_qualified_vs._relative_paths). – Igor Apr 12 '18 at 14:34
  • Using a relative path would be the better option it seems than installing the datbase elsewhere. How can i find out my current relative path? So i can know where to being. – Aaron Moriarty Apr 12 '18 at 14:39
  • There is also a helpful [`SqlConnectionStringBuilder`](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder(v=vs.110).aspx) class that can let you easily modify different parts of the connection string without having to deal with parsing it yourself. – Bradley Uffner Apr 12 '18 at 14:44
  • after looking at that post i have solved my problem using his verified answer, thank you. – Aaron Moriarty Apr 13 '18 at 10:43

0 Answers0