Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Connection String Without Password Value in C#

I try create method for get the connection string value but without value for password, or show password like * character. I need used it in logging.

I use ConnectionStringBuilder for Oracle, SqlServer.

Anyway, another way -better- to implement it ? Maybe more generic . And what it happens it ProviderName is empty...

public static string GetConnectionStringWithouPassword(this ConnectionStringSettings cs)
{
    if (cs == null || string.IsNullOrEmpty(cs.ConnectionString)) return null;

    if (cs.ProviderName.ToLower().Equals("Oracle.DataAccess.Client".ToLower()))
    {
        var builderOra = new Oracle.DataAccess.Client.OracleConnectionStringBuilder(cs.ConnectionString);
        return "";
    }

    if (cs.ProviderName.ToLower().Equals("System.Data.SqlClient".ToLower()))
    {
        var builderSql = new SqlConnectionStringBuilder(cs.ConnectionString);
        return "";
    }

    return null;
}

//
public static string ObtenerCadenasConexion()
{
    var sb = new StringBuilder();
    ConnectionStringSettingsCollection settings = ConfigurationManager.ConnectionStrings;

    if (settings != null)
    {
        foreach (ConnectionStringSettings cs in settings)
        {
            sb.AppendLine("Name: " + cs.Name);
            sb.AppendLine("ProviderName: " + cs.ProviderName);
            sb.AppendLine("ConnectionString: " + cs.GetConnectionStringWithouPassword() + Environment.NewLine);
        }
    }

    return sb.ToString();
}
like image 961
Kiquenet Avatar asked Jan 19 '23 11:01

Kiquenet


1 Answers

check this one: DbConnectionStringBuilder Class

you can use the Remove method, no magic parsing required:

for example, from that MSDN page:

static void Main()
{
    DbConnectionStringBuilder builder = new
        DbConnectionStringBuilder();
    builder.ConnectionString =
        @"Provider=Microsoft.Jet.OLEDB.4.0;Data 
            Source=C:\Demo.mdb;" +
        "Jet OLEDB:System Database=system.mdw;";

    // Try to remove an existing item.
    TryRemove(builder, "Provider");

    // Try to remove a nonexistent item.
    TryRemove(builder, "User ID");

    // Try to remove an existing item, 
    // demonstrating that the search isn't 
    // case sensitive.
    TryRemove(builder, "DATA SOURCE");
    Console.ReadLine();
}

static void TryRemove(DbConnectionStringBuilder builder, string itemToRemove)
{
    if (builder.Remove(itemToRemove))
    {
        Console.WriteLine(@"Removed '{0}'", itemToRemove);
    }
    else
    {
        Console.WriteLine(@"Unable to remove '{0}'", itemToRemove);
    }
    Console.WriteLine(builder.ConnectionString);
}
like image 129
Davide Piras Avatar answered Jan 21 '23 16:01

Davide Piras