locked
Sqlconnection string RRS feed

  • Question

  • SqlConnectioncnn =newSqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Urgen\Documents\Lib.mdf;Integrated Security=True;Connect Timeout=30");

    Above is my code snippet to connect to a local database. How would i make my application to navigate Lib.mdf from documents folder dynamically, because user names vary from machine to machine. In other word i wanted to make my database location without referring to a user's name specific..

    Thanks

    Wednesday, November 26, 2014 6:02 AM

Answers

  • Hi Urgen,

    To get current user path, you can use Environment.SpecialFolder. Like the following

    Environment.SpecialFolder.MyDocuments

    So your code should be like this

    string attachDbFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    
                SqlConnection cnn = new SqlConnection(string.Format(@"Data Source=(LocalDB)\v11.0;AttachDbFilename= {0}\Lib.mdf;Integrated Security=True;Connect Timeout=30",attachDbFilePath));

    Have a nice day!

    Kristin


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by UrgenKalsang Thursday, November 27, 2014 8:46 AM
    Thursday, November 27, 2014 2:18 AM

All replies

  • Hi Urgen,

    To get current user path, you can use Environment.SpecialFolder. Like the following

    Environment.SpecialFolder.MyDocuments

    So your code should be like this

    string attachDbFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    
                SqlConnection cnn = new SqlConnection(string.Format(@"Data Source=(LocalDB)\v11.0;AttachDbFilename= {0}\Lib.mdf;Integrated Security=True;Connect Timeout=30",attachDbFilePath));

    Have a nice day!

    Kristin


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by UrgenKalsang Thursday, November 27, 2014 8:46 AM
    Thursday, November 27, 2014 2:18 AM
  • You need to have at least SQL Server Express installed instead of using local DB.

    The connection string for SQL Server you can find them here:

    https://curah.microsoft.com/261804/connection-string-for-ms-sql-server

    chanmm


    chanmm

    • Proposed as answer by chanmmMVP Thursday, November 27, 2014 2:41 AM
    Thursday, November 27, 2014 2:40 AM