Csharp:read system DSN configured get Driver Names on Windows

Source: Internet
Author: User
Tags dsn sybase visual studio 2010

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 {[Dllimp ORT ("ODBC32")] public static extern short Sqlallochandle (short handletype, IntPtr Inputhandle, out IntPtr Outputhan        DLE); [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 Environmenthandl E, ushort Direction, StringBuilder ServerName, short BufferLength1, ref short namelength1ptr, StringBuilder Description, S        Hort BufferLength2, ref short namelength2ptr); [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 Sqlgetinstal        LEDDRIVERSW (char[] lpszbuf, ushort Cbufmax, out ushort pcbbufout);        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 sql_attr_odbc_version = 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 bu            Tton1_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, 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, Sql_attr_odbc_version, (INTPTR) 3, 0);                if (Iresult = = sql_success) {ODBCSTR sr = null;                Iresult = Sqldatasources (lhenv, Sql_fetch_first, Sdsnitem, 1024x768, ref idsnlen, Sdrvitem, 1024x768, ref Idrvlen);                    while (Iresult = = sql_success) {sr=new odbcstr ();                    MessageBox.Show (Sdsnitem.tostring (), "sdsnitem.tostring ()");                    Iresult = Sqldatasources (lhenv, Sql_fetch_next, Sdsnitem, 1024x768, ref idsnlen, Sdrvitem, 1024x768, ref Idrvlen); Sr.                    DSNname = Sdsnitem.tostring (); Sr.                    DriveName = Sdrvitem.tostring ();                    String str = "Server=home\0dsn=mydsn\0description=mydsndesc\0database=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 Sqlgetinsta Lleddrivers was successfull; NULL, otherwise.</returns> public static string[] Getodbcdrivernames () {string[] Odbcdrive            Rnames = 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 (' + ');        } return odbcdrivernames;    }}///<summary>//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 String;            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 Ju Wen");            String sss = Connbuilder.tostring ();            MessageBox.Show (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 succeeded!            "); } catch (Exception ex) {MessageBox.Show (ex.            Message.tostring ()); } finally {Conn.            Close ();        }//Set//odbcconnectionstringbuilder.dsn=connectionstring; }//<summary>///</summary>/<param name= "Database" ></param&gt        ; <param name= "Version" ></param>///<returns></returns> public static string Geto            Dbcdrivername (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 ins             Talled ");       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\visual Studio 2010\projects\ sqlanywheredemo\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 (odbcconnections tringbuilder.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 ()); }               }    }

  

Csharp:read system DSN configured get Driver Names on Windows

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.