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

本文关键字:连接 字符串 密码 获取 | 更新日期: 2023-09-27 18:11:42

我尝试创建方法来获取连接字符串值,但没有密码值,或显示密码,如*字符。我需要在日志中使用它。

我使用ConnectionStringBuilder 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();
}

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

检查这个: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);
}

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