get user id from sql connection+C#+window application

Hi All,
i get the sql connection from an ocx object.
how i can get the user ID from sql connection.

Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

brutaldevConnect With a Mentor Commented:
Nope, you will always get an empty string for SqlConnectionStringBuilder.Password unless you've set it yourself. Check my previous comment above.

Integrated security is an option to use your Windows account to login instead of providing a password in the connection string.

I thought you wanted to get the User ID which you can easily get using the connection string builder? If you want to get the password you're going to have to parse the connection string manually by splitting it and looking for 'Password'

Warranty: You should probably do a lot more checks in this code to make sure it doesn't fall over when it can't find the password, this is just an example.
using System.Linq;

string connectionString = "Data Source=mkitani;Initial Catalog=Test;Integrated Security=false;User ID=testUser;Password=123; TimeOut=20;";
string passwordSection = connectionString.Split(';').First(s => s.Trim().StartsWith("password", StringComparison.OrdinalIgnoreCase));
string password = password = passwordSection.Split('=')[1];  // Second half of the =

Open in new window

If you already have the connection object (SqlConnection) then you can pas the connection string into a SqlConnectionBuilder to get the User ID that is being used to connect
SqlConnection conn = GetYourConnetion();
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(conn.ConnectionString);
string userID = builder.UserID;

Open in new window

MKItaniAuthor Commented:
this is my connectionString:
<add name="ReportManagerLibrary"
                  connectionString="Data Source=mkitani;Initial Catalog=Test;Integrated Security=false;User ID=testUser;Password=123; TimeOut=20;"
                  providerName="System.Data.SqlClient" />

but always when i am using "builder.Password" i get an empty string Why????
The new generation of project management tools

With’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

This is documented behavior for the Password property.

If the value has not been set and the developer tries to retrieve the property, the return value is String.Empty.
This is obviously for security reasons, if you pull a connection string into the builder the password is not visible unless you set it manually.
MKItaniAuthor Commented:
so in case the integrated Security in the connection string is false always i get an empty string when i used SqlConnectionStringBuilder.Password
All Courses

From novice to tech pro — start learning today.