我正在开发一个具有 C++ 扩展存储过程的遗留应用程序。此 xsproc 使用 ODBC 连接到数据库,这意味着它需要配置 DSN。
我正在更新安装程序(使用 Visual Studio 2008 安装项目创建),并希望有一个可以创建 ODBC DSN 条目的自定义操作,但我很难在 Google 上找到有用的信息。
任何人都可以帮忙吗?
我最终通过操纵注册表自己解决了这个问题。我创建了一个包含功能的类,我在这里包含了它的内容:
///<summary>
/// Class to assist with creation and removal of ODBC DSN entries
///</summary>
public static class ODBCManager
{
private const string ODBC_INI_REG_PATH = "SOFTWARE\\ODBC\\ODBC.INI\\";
private const string ODBCINST_INI_REG_PATH = "SOFTWARE\\ODBC\\ODBCINST.INI\\";
/// <summary>
/// Creates a new DSN entry with the specified values. If the DSN exists, the values are updated.
/// </summary>
/// <param name="dsnName">Name of the DSN for use by client applications</param>
/// <param name="description">Description of the DSN that appears in the ODBC control panel applet</param>
/// <param name="server">Network name or IP address of database server</param>
/// <param name="driverName">Name of the driver to use</param>
/// <param name="trustedConnection">True to use NT authentication, false to require applications to supply username/password in the connection string</param>
/// <param name="database">Name of the datbase to connect to</param>
public static void CreateDSN(string dsnName, string description, string server, string driverName, bool trustedConnection, string database)
{
// Lookup driver path from driver name
var driverKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + driverName);
if (driverKey == null) throw new Exception(string.Format("ODBC Registry key for driver '{0}' does not exist", driverName));
string driverPath = driverKey.GetValue("Driver").ToString();
// Add value to odbc data sources
var datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + "ODBC Data Sources");
if (datasourcesKey == null) throw new Exception("ODBC Registry key for datasources does not exist");
datasourcesKey.SetValue(dsnName, driverName);
// Create new key in odbc.ini with dsn name and add values
var dsnKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + dsnName);
if (dsnKey == null) throw new Exception("ODBC Registry key for DSN was not created");
dsnKey.SetValue("Database", database);
dsnKey.SetValue("Description", description);
dsnKey.SetValue("Driver", driverPath);
dsnKey.SetValue("LastUser", Environment.UserName);
dsnKey.SetValue("Server", server);
dsnKey.SetValue("Database", database);
dsnKey.SetValue("Trusted_Connection", trustedConnection ? "Yes" : "No");
}
/// <summary>
/// Removes a DSN entry
/// </summary>
/// <param name="dsnName">Name of the DSN to remove.</param>
public static void RemoveDSN(string dsnName)
{
// Remove DSN key
Registry.LocalMachine.DeleteSubKeyTree(ODBC_INI_REG_PATH + dsnName);
// Remove DSN name from values list in ODBC Data Sources key
var datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + "ODBC Data Sources");
if (datasourcesKey == null) throw new Exception("ODBC Registry key for datasources does not exist");
datasourcesKey.DeleteValue(dsnName);
}
///<summary>
/// Checks the registry to see if a DSN exists with the specified name
///</summary>
///<param name="dsnName"></param>
///<returns></returns>
public static bool DSNExists(string dsnName)
{
var driversKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + "ODBC Drivers");
if (driversKey == null) throw new Exception("ODBC Registry key for drivers does not exist");
return driversKey.GetValue(dsnName) != null;
}
///<summary>
/// Returns an array of driver names installed on the system
///</summary>
///<returns></returns>
public static string[] GetInstalledDrivers()
{
var driversKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + "ODBC Drivers");
if (driversKey == null) throw new Exception("ODBC Registry key for drivers does not exist");
var driverNames = driversKey.GetValueNames();
var ret = new List<string>();
foreach (var driverName in driverNames)
{
if (driverName != "(Default)")
{
ret.Add(driverName);
}
}
return ret.ToArray();
}
}
在chrfalch 的帖子之后,这里是一些用于更新 DSN 的示例代码(我知道 OP 要求创建,但是此代码很容易转换为您需要做的任何事情),使用 API 调用而不是通过注册表直接(使用来自pinvoke.net 页面的信息):-
[DllImport("ODBCCP32.DLL", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool SQLConfigDataSourceW(UInt32 hwndParent, RequestFlags fRequest, string lpszDriver, string lpszAttributes);
enum RequestFlags : int
{
ODBC_ADD_DSN = 1,
ODBC_CONFIG_DSN = 2,
ODBC_REMOVE_DSN = 3,
ODBC_ADD_SYS_DSN = 4,
ODBC_CONFIG_SYS_DSN = 5,
ODBC_REMOVE_SYS_DSN = 6,
ODBC_REMOVE_DEFAULT_DSN = 7
}
bool UpdateDsnServer(string name, string server)
{
var flag = RequestFlags.ODBC_CONFIG_SYS_DSN;
string dsnNameLine = "DSN=" + name;
string serverLine = "Server=" + server;
string configString = new[] { dsnNameLine, serverLine }.Aggregate("", (str, line) => str + line + "\0");
return SQLConfigDataSourceW(0, flag, "SQL Server", configString);
}
有一个 API 可以做这样的事情。使用 API 还将确保您的应用程序与较新版本的 Windows 保持兼容。API 可以在这里找到:
http://msdn.microsoft.com/en-us/library/ms716476(VS.85).aspx
可以在 PInvoke.net 上找到在 c# 中调用此函数的 PInvoke。
有一个关于读取 ODBC 信息的 CodeProject 页面。
阅读它应该为您提供逆向工程编写所需的注册表项所需的信息。
从那个代码;
private const string ODBC_LOC_IN_REGISTRY = "SOFTWARE\\ODBC\\";
private const string ODBC_INI_LOC_IN_REGISTRY =
ODBC_LOC_IN_REGISTRY + "ODBC.INI\\";
private const string DSN_LOC_IN_REGISTRY =
ODBC_INI_LOC_IN_REGISTRY + "ODBC Data Sources\\";
private const string ODBCINST_INI_LOC_IN_REGISTRY =
ODBC_LOC_IN_REGISTRY + "ODBCINST.INI\\";
private const string ODBC_DRIVERS_LOC_IN_REGISTRY =
ODBCINST_INI_LOC_IN_REGISTRY + "ODBC Drivers\\";
为 Barnwell 的代码 +1!
但是,我认为他的 DSNExists() 正在查询错误的键。我认为应该是这样的:
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");
return sourcesKey.GetValue(dsnName) != null;
}
感谢您提供此代码,我自己使用过。我不得不改变两件艰难的事情:
为了获得driverName
我必须使用OpenSubKey
而不是CreateSubKey
获取值:
// Lookup driver path from driver name
var driverKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
ODBCINST_INI_REG_PATH + driverName);
由于我运行的是 Vista,我必须使用应用程序清单并将其设置requestedPrivileges
为:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
以下文章帮助我找到了OpenSubKey
问题:http ://www.daveoncsharp.com/2009/08/read-write-delete-from-windows-registry-with-csharp/
谢谢,如果你正在制作一个 dsn 到 excel,这是一个很大的帮助,也许需要添加这样的东西
var dsnKeyEng = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + dsnName + "\\Engines");
var dsnKeyExl = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + dsnName + "\\Engines\\Excel");
dsnKeyExl.SetValue("FirstRowHasNames", 01);
dsnKeyExl.SetValue("MaxScanRows", 8);
dsnKeyExl.SetValue("Threads",3);
dsnKeyExl.SetValue("UserCommitSync", "Yes")