[英]Is it possible to create a ODBC System DSN from C# using SQLConfigDataSourceW?
[英]How do I create an ODBC DSN entry using C#?
我正在研究具有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#中調用此函數。
為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;
}
閱讀它應該為您提供逆向工程編寫所需注冊表項所需的信息。
從那個代碼;
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\\";
感謝您提供此代碼,我自己也使用過它。 我不得不改變兩件事:
要獲取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 : OpenSubKey
感謝這是一個很好的幫助,如果你正在使用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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.