Reputation: 43
I need to create ODBC DSN connections from C# programmatically. I've gotten the following code working, which uses the SQLConfigDataSourceW function to create an ODBC DSN connection.
public class OdbcWrapper
{
[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
}
public bool UpdateDsnServer(string name, string server)
{
var flag = RequestFlags.ODBC_ADD_DSN;
string dsnNameLine = "DSN=" + name;
string serverLine = "Server=" + server;
string trusted = "Trusted_Connection=YES";
string configString = new[] { dsnNameLine, serverLine,trusted }.Aggregate("", (str, line) => str + line + "\0");
return SQLConfigDataSourceW(0, flag, "SQL Server", configString);
}
}
Which I can the call using:
var odbc = new OdbcWrapper();
bool test = odbc.UpdateDsnServer("TEST_DSN_NAME", "TEST_SERVER_NAME");
MessageBox.Show(test.ToString());
This works for ODBC_ADD_DSN = 1
where a User DSN is created and returns test = true
, but when I change the flag to ODBC_ADD_SYS_DSN = 4
it returns test = false
and no System DSN is created, both cases confirmed by checking the ODBC Data Source Administrator.
Upvotes: 1
Views: 1488
Reputation: 43
Running the application with elevated permissions allows a system DSN to be created. The code above works as is, but the application was missing the permissions elevation that were requested in the ODBC Data Source Administrator. Once running with the correct permissions, the code replicates the functionality of creating, deleting, and configuring user, file, and system DSNs.
Upvotes: 2