在C#中获取没有密码值的连接字符串

时间:2011-10-20 09:12:05

标签: c# ado.net refactoring database-connection connection-string

我尝试使用create方法获取连接字符串值,但没有密码值,或者显示像*字符这样的密码。我需要在记录中使用它。

我使用ConnectionStringBuilder for Oracle,SqlServer。

无论如何,另一种方式 - 更好 - 实施它?也许更通用。它发生了什么,ProviderName是空的......

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();
}

2 个答案:

答案 0 :(得分:6)

检查一下:DbConnectionStringBuilder Class

你可以使用Remove方法,不需要魔术解析:

例如,从该MSDN页面:

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);
}

答案 1 :(得分:1)

检查Connection.PersistSecurityInfo属性,您可以在自动创建连接后立即删除此信息。