I have created a local DB programmatically using Winforms (c#) and added tables, stored procedures to it, and stored on the user's preferable location. Now, all I want is to make my Winforms app access it using without opening visual studio or SSMS to get the connection string for that database.
My try: I did open the visual studio to get the database's connection string to add it to the WinForms app's connection string and I want to make transactions with it.
Is there any way to programmatically retrieve the connection string of the user-selected database from the Winforms application?
Like,
- User chooses the location of already created localdatabase.mdf from his WinForms app.
- The application retrieves the connection string so that he can use it to connect to the database.
The retrieval can be of parts like only retrieving the Data Source
for the database. I can manage to build the connection string with it. Like using the name of the file for Initial Catalog
and adding Integrated security
using strings.
Any ideas regarding this will really help. Thank guys.
CodePudding user response:
You can get and edit the connection string using SqlConnectionStringBuilder Class.
Here the connection string is local to the method but any place in scope of the method below.
public static void ChangeConnectionStringFromExisting()
{
var connectionString = "Server=localhost;Integrated security=SSPI;database=master";
var builder = new SqlConnectionStringBuilder(connectionString);
builder.DataSource = "(LocalDB)\\MSSQLLocalDB";
builder.InitialCatalog = "MyAppDatabase.mdf";
connectionString = builder.ConnectionString;
using (var cn = new SqlConnection(connectionString))
{
// . . .
}
}