Question

How to get server name through code if SQL Server (Standard Edition) is installed.

We pass the server name while creating a connection string to connect SQL Server. Can we retrieve this value through code?

string sqlConnectionString = string.Format(
"user id={0};password={1};server={2};Trusted_Connection=no;database=TestDB;
connection timeout={3}",
dirDBinfo.UserName, dirDBinfo.Password, "ServerName", dirDBinfo.TimeOut);
Was it helpful?

Solution

I'm not sure I understand what you want.

If you already have a connection string, and you are trying to extract the server name from it for use elsewhere, you can reverse-engineer it like so:

var parser = new SqlConnectionStringBuilder(connectionString);
var serverName = parser.DataSource;

If you are constructing your connection string for the first time, then:

  1. If you know that you want to connect to the SQL Server on the machine that your client code is executing on, then just use (local) for the server name. If the SQL Server has an instance name, then specify it like this: (local)\myinstancename.
  2. If you don't know in advance what server to connect to, then it's up to you to obtain that information from somewhere else.

OTHER TIPS

Can't you just execute SELECT @@SERVERNAME against this connection?

Is the server on the local computer?
If so, set the server name to localhost.
If not, use SqlDataSourceEnumerator.


Also, instead of building a connection string using String.Format, you should use a SqlConnectionStringBuilder. This will handle values with semicolons.

For example:

var builder = new SqlConnectionStringBuilder();

builder.UserID = dirDBinfo.UserName;
builder.Password = dirDBinfo.Password;
builder.Server= "localhost";
builder.UserID = dirDBinfo.UserName;
builder["Trusted_Connection"] = "no";
builder.Database = "TestDB"
builder.ConnectTimeout = dirDBinfo.TimeOut;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top