Csharp: read system DSN configured get Driver Names on windows, csharpconfigured
Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. text; using System. windows. forms; using System. runtime. interopServices; using Microsoft. win32; using System. data. odbc; namespace SQLanyWhereDemo {public partial class Form5: Form {[DllImport ("odbc32")] public static extern short SQLAllocHandle (short HandleType, IntPtr InputHandle, out IntPtr OutputHandle ); [DllImport ("odbc32", CharSet = CharSet. unicode)] public static extern short SQLSetEnvAttr (IntPtr envHandle, ushort attribute, IntPtr val, int stringLength); [DllImport ("odbc32.dll", CharSet = CharSet. ansi)] public static extern short SQLDataSources (IntPtr statistics, ushort ction, StringBuilder ServerName, short BufferLength1, ref short NameLength1Ptr, StringBuilder Description, short bufferlengyy, ref short statistics ); [DllImport ("ODBCCP32.dll")] private static extern bool SQLConfigDataSource (IntPtr parent, int request, string driver, string attributes); [DllImport ("odbccp32.dll", CharSet = CharSet. unicode, SetLastError = true)] private static extern bool SQLGetInstalledDriversW (char [] lpszBuf, ushort cbufMax, out ushort writable bufout); public const int SQL _SUCCESS = 0; public const int SQL _ERROR =-1; public const int SQL _FETCH_NEXT = 1; public const int SQL _FETCH_FIRST = 2; public const int SQL _FETCH_FIRST_USER = 31; public const int SQL _FETCH_FIRST_SYSTEM = 32; public const int handle = 200; public const int SQL _HANDLE_ENV = 1; public const int SQL _HANDLE_DBC = 2; public const int SQL _HANDLE_STMT = 3; public const int SQL _HANDLE_DESC = 4; /// <summary> ///// </summary> public Form5 () {InitializeComponent ();} /// <summary> //// </summary> /// <param name = "sender"> </param> /// <param name = "e "> </param> private void button#click (object sender, eventArgs e) {List <ODBCStr> ls = new List <ODBCStr> (); short iResult = 0; IntPtr lhEnvIn = (IntPtr) 0; IntPtr lhEnv = (IntPtr) 0; stringBuilder sDSNItem = new StringBuilder (1024); StringBuilder sDRVItem = new StringBuilder (1024); short iDSNLen = 0; short iDRVLen = 0; SQLSetEnvAttr (lhEnv, 200, (IntPtr) 3, 0); iResult = SQLAllocHandle (1, lhEnvIn, out lhEnv); MessageBox. show (iResult. toString (), "iResult SQLAllocHandle"); // short iResult = 0; // IntPtr lhEnvIn = (IntPtr) 0; // IntPtr lhEnv = (IntPtr) 0; // StringBuilder sDSNItem = new StringBuilder (1024); // StringBuilder sDRVItem = new StringBuilder (1024); // short iDSNLen = 0; // short iDRVLen = 0; iResult = SQLAllocHandle (SQL _HANDLE_ENV, lhEnvIn, out lhEnv); SQLSetEnvAttr (lhEnv, distance, (IntPtr) 3, 0); if (iResult = SQL _SUCCESS) {ODBCStr sr = null; iResult = SQLDataSources (lhEnv, SQL _FETCH_FIRST, sDSNItem, 1024, ref iDSNLen, sDRVItem, 1024, ref iDRVLen); while (iResult = SQL _SUCCESS) {sr = new ODBCStr (); // MessageBox. show (sDSNItem. toString (), "sDSNItem. toString () "); iResult = SQLDataSources (lhEnv, SQL _FETCH_NEXT, sDSNItem, 1024, ref iDSNLen, sDRVItem, 1024, ref iDRVLen); sr. dsnName = sDSNItem. toString (); sr. driveName = sDRVItem. toString (); // string str = "SERVER = HOME \ 0DSN = MYDSN \ 0 DESCRIPTION = MYDSNDESC \ 0 DATABASE = DBServer \ 0TRUSTED_CONNECTION = YES"; // SQLConfigDataSource (IntPtr) 0, 4, "Sybase SQL Anywhere 5.0", str); // SQL Server // MessageBox. show (str); ls. add (sr) ;}} this. dataGridView1.DataSource = ls ;} /// <summary> //// </summary> /// <param name = "sender"> </param> /// <param name = "e "> </param> private void button2_Click (object sender, eventArgs e) {string [] list = GetOdbcDriverNames ();} // <summary> // Gets the ODBC driver names from the SQLGetInstalledDrivers function. /// </summary> /// <returns> a string array containing the ODBC driver names, if the call to SQLGetInstalledDrivers was successfull; null, otherwise. </returns> public static string [] GetOdbcDriverNames () {string [] odbcDriverNames = null; char [] driverNamesBuffer = new char [ushort. maxValue]; ushort size; bool succeeded = SQLGetInstalledDriversW (driverNamesBuffer, ushort. maxValue, out size); if (succeeded = true) {char [] driverNames = new char [size-1]; Array. copy (driverNamesBuffer, driverNames, size-1); odbcDriverNames = (new string (driverNames )). split ('\ 0');} return odbcDriverNames ;}} /// <summary> /// tu juwen // 20180223 // Geovin Du /// </summary> public class ODBCStr {// <summary> /// /// </summary> public string DriveName {get; set ;}//< summary >///// </summary> public string DsnName {get; set ;} /// <summary> ///// </summary> public string ServerName {get; set ;} /// <summary> ///// </summary> public string DatabaseName {get; set ;} /// <summary> ///// </summary> public string DataSrource {get; set ;} /// <summary >///// </summary> public string DataFile {get; set ;}}}
/// <Summary> //// </summary> /// <param name = "sender"> </param> /// <param name = "e "> </param> private void button3_Click (object sender, eventArgs e) {// string connectionString = "dsn = LocalServer"; // System. data. common. dbConnectionStringBuilder builder = new System. data. common. dbConnectionStringBuilder (); // builder. connectionString = connectionString; // string server = builder ["Data Source"] as s Tring; // string database = builder ["Initial Catalog"] as string; // string conString = "SERVER = localhost; DATABASE = tree; UID = root; PASSWORD = branch; min Pool Size = 0; Max Pool Size = 200 "; // SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder (conString); // string user = builder. userID; // string pass = builder. password; // OdbcConnectionStringBuilder buil = new OdbcConnectionStringBuilder (); // Buil. driver = "Sybase SQL Anywhere 5.0"; // buil. dsn = "achive"; System. data. odbc. odbcConnectionStringBuilder connBuilder = new System. data. odbc. odbcConnectionStringBuilder (); connBuilder. dsn = "achive"; connBuilder. driver = "Sybase SQL Anywhere 5.0"; // connBuilder. add ("uid", ""); // connBuilder. add ("pwd", ""); connBuilder. add ("database", "tu juwen"); string sss = connBuilder. toString (); // MessageBox. S How (connBuilder. toString (); System. data. odbc. odbcConnection conn = new System. data. odbc. odbcConnection (connBuilder. toString (); try {conn. open (); System. data. odbc. odbcCommand comm = new System. data. odbc. odbcCommand ("select count (*) from item_description", conn); var reader = comm. executeReader (); while (reader. read () {MessageBox. show (reader [0]. toString ();} MessageBox. show ("connection successful! ");} Catch (Exception ex) {MessageBox. show (ex. message. toString ();} finally {conn. close ();} // set // OdbcConnectionStringBuilder. dsn = connectionString ;} /// <summary> //// </summary> /// <param name = "Database"> </param> /// <param name = "Version "> </param> // <returns> </returns> public static string GetODBCDriverName (string Database, string Version) {string ODBCDriverName = ""; RegistryKey registryKey = Registry. localMachine; RegistryKey registrySubKey = registryKey. openSubKey (@ "SOFTWARE \ ODBC \ ODBCINST. INI \ "); String [] SubKeyNames = registrySubKey. getSubKeyNames (); foreach (String KeyName in SubKeyNames) {if (KeyName. contains (Database) & KeyName. contains (Version) {ODBCDriverName = KeyName; break ;}} registrySubKey. close (); registryKey. close (); return ODBCDriverName ;} /// <summary> //// </summary> /// <param name = "sender"> </param> /// <param name = "e "> </param> private void button4_Click (object sender, eventArgs e) {OdbcConnectionStringBuilder odbcConnectionStringBuilder = new OdbcConnectionStringBuilder (); OdbcCommand odbcCommand; int RecordFound = 0; odbcConnectionStringBuilder. driver = GetODBCDriverName ("Sybase SQL Anywhere", "5.0"); if (odbcConnectionStringBuilder. driver = "") {MessageBox. show ("ODBC Driver is not installed"); // return-1;} odbcConnectionStringBuilder. add ("DSN", "achive"); // odbcConnectionStringBuilder. add ("UID", "no-user"); // odbcConnectionStringBuilder. add ("PWD", "no-pass"); odbcConnectionStringBuilder. add ("DB", @ "C: \ Documents and Settings \ geovindu \ My Documents ents \ Visual Studio 2010 \ Projects \ SQLanyWhereDemo \ bin \ Debug \ geovindu. db; "); // copy of database SPORTS odbcConnectionStringBuilder. add ("HOST ",". "); // odbcConnectionStringBuilder. add ("PORT", "5162"); // I found this port inn the log file using (OdbcConnection connection = new OdbcConnection (odbcConnectionStringBuilder. connectionString) {connection. open (); try {odbcCommand = new OdbcCommand ("select count (*) FROM pub. invoice WHERE Invoicenum> 0 ", connection); odbcCommand. commandTimeout = 1; object executeScalarResult = odbcCommand. executeScalar (); RecordFound = Convert. toInt32 (executeScalarResult);} catch (Exception ex) {MessageBox. show (ex. message. toString ());}}}