Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How we get local SQL Server instance through c#

Tags:

c#

sql-server

I am creating a Windows app in which I need to create a connection string automatically. I create a Windows form similar to SQL Server Management Studio Connect to server form. For this I need few things

  1. local SQL server Name of the system.

  2. After user fill the form like select server Name and authentication type then i need to check that that filled details are correct.

  3. I need to create automatic connection string in c# and create automatic database and for this I execute SQL query in c# code that are working fine.

So help me get the instance name and check the data is valid in C# window application.

like image 872
Deshraj sharma Avatar asked May 06 '26 05:05

Deshraj sharma


1 Answers

To get all instances of local network (and local) you can use this code: (from MSDN)

SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();

And to test connection string you can simply open a connection with generated connection string. like this: (from this answer)

string provider = "System.Data.SqlClient"; // for example
DbProviderFactory factory = DbProviderFactories.GetFactory(provider);
using(DbConnection conn = factory.CreateConnection()) {
    conn.ConnectionString = cs;
    conn.Open();
}
like image 123
farid bekran Avatar answered May 08 '26 03:05

farid bekran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!