我一直在使用注册表来检查给定的 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;
}
绝对不存在 0 个 DSN,并且我作为参数传入的 DSN 确实存在,但它返回 false。我不明白为什么?
我正在寻找如何在 PowerShell 中执行此操作,虽然这不是这个问题的严格答案,但因为它确实出现在我的搜索中,我想我可以在这里留言:
if ( (Get-OdbcDsn -Name $DSN -CimSession $OnHost -ErrorAction Ignore) -ne $null)
{
# Code here runs if the DSN exists.
}
可以添加额外参数来检查特定平台。
首先你要知道运行程序的机器是 x86 还是 x64:
/// <summary>
/// Determines if the current application is 32 or 64-bit.
/// se retorno == 32 = x86 else x64
/// </summary>
public int Bits()
{
return IntPtr.Size * 8;
}
之后,设置注册表路径。我为我的应用程序所做的作用是使用变量 is64 作为 int。如果变量被赋值为 32,则系统为 x86,否则为 x64
/// <summary>
/// Construtor da classe
/// a variavel is64 vai receber um numero inteiro (32 ou 64) representando a arquitetura da maquina
/// </summary>
/// <param name="is64"></param>
public Odbc(int is64)
{
if (is64 == 32)
{
this.ODBC_INI_REG_PATH = "Software\\ODBC\\ODBC.INI\\";
this.ODBCINST_INI_REG_PATH = "Software\\ODBC\\ODBCINST.INI\\";
}
else
{
this.ODBC_INI_REG_PATH = "Software\\Wow6432Node\\ODBC\\ODBC.INI\\";
this.ODBCINST_INI_REG_PATH = "Software\\Wow6432Node\\ODBC\\ODBCINST.INI\\";
}
}
最后我修改了你放在主题上的功能。修改为:
Registry.LocalMachine.CreateSubKey =>Registry.LocalMachine.OpenSubKey
public bool DSNExists(string dsnName)
{
try
{
var sourcesKey = Registry.LocalMachine.OpenSubKey(this.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;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
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.GetSubKeyNames();
Console.WriteLine("length: " + blah.Length);
var dsnKey = sourcesKey.OpenSubKey(dsnName);
bool exists = (dsnKey != null);
if (exists) dsnKey.Close();
sourcesKey.Close();
return exists;
}
请注意
我想知道如何使用PowerShell检查DSN是否存在,因为我想避免在DSN不存在时尝试使用Remove-OdbcDsn时出现的错误消息。现在,我不再尝试检查它是否存在,而是使用“-ErrorAction Ignore”运行Remove-OdbcDsn。如果 DSN 存在,则将其删除;如果没有,脚本就会默默地继续前进。完美的! 谢谢@奥斯卡·伯格伦。