3

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

3

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();
}
Community
  • 1
  • 1
farid bekran
  • 2,684
  • 2
  • 16
  • 29
1

use ManagedComputer,

using Microsoft.SqlServer.Management.Smo.Wmi;

ManagedComputer mc = new ManagedComputer();

foreach (ServerInstance si in mc.ServerInstances)
{
     Console.WriteLine("The installed instance name is " + si.Name);
}
Imran Ali Khan
  • 8,469
  • 16
  • 52
  • 77
  • I've used this namespace right now , but there is an error highlighting under "Management". The error is showing that "This type or namespace does not exist under Microsoft.SqlServer ". Please confirm ! My sql server version is 2008. – Kiran RS Sep 15 '15 at 08:19
  • see https://askgarth.com/blog/how-to-install-the-sql-server-wmi-provider/ – BenHero Nov 11 '21 at 07:12