检查 ODBC DSN 是否存在?

Ben*_*Ben 3 c# odbc dsn

我一直在使用注册表来检查给定的 DSN 是否存在,使用以下代码:

private const string ODBC_INI_REG_PATH = "SOFTWARE\\ODBC\\ODBC.INI\\";
public static bool DSNExists(string dsnName)
{
    var sourcesKey = Registry
        .LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + "ODBC Data Sources");
    if (sourcesKey == null) 
        throw new Exception("ODBC Registry key for sources does not exist");
    string[] blah = sourcesKey.GetValueNames();
    Console.WriteLine("length: " + blah.Length); //prints: 0
    return sourcesKey.GetValue(dsnName) != null;
}
Run Code Online (Sandbox Code Playgroud)

绝对不存在 0 个 DSN,并且我作为参数传入的 DSN 确实存在,但它返回 false。我不明白为什么?

Osk*_*ren 6

我正在寻找如何在 PowerShell 中执行此操作,虽然这不是这个问题的严格答案,但由于它确实出现在我的搜索中,我想我可以在这里留下注释:

if ( (Get-OdbcDsn -Name $DSN -CimSession $OnHost -ErrorAction Ignore) -ne $null)
{
    # Code here runs if the DSN exists.
}
Run Code Online (Sandbox Code Playgroud)

可以添加附加参数来检查特定平台。

  • 我不是 PowerShell 人员,但我相信这是当前所需要的。请注意“ErrorAction”,这样它就不会向控制台吐出,并且“ne”,而不是“neq”:“if ((Get-OdbcDsn -Name $DSN -CimSession $OnHost -ErrorAction SilentlyContinue) -ne $null)” (2认同)