简体   繁体   中英

WPF, What's the best way to store a constant to be used at startup?

I have a WPF application that accesses a database instance. I develop on my personal machine and the application will run on another machine and database instance. Is there a way or best practice for storing the instance name outside of the WPF application that I can read upon app startup? Currently I have comment and uncomment the database instance name as I move from machine to machine. I would like to have something stored on the local machine that I can just read when the application is launched.

Here is what I currently do:

try
        {
            if (sqlConn != null)
            {
                sqlConn.Close();
            }

            strConnection = "Data Source=" + strDBInstance + "; Initial Catalog=NBFoodPantry;Integrated Security=true; MultipleActiveResultSets = True";
            //strConnection = "Data Source=CASS-LAPTOP\\SQLEXPRESS; Initial Catalog=NBFoodPantry;Integrated Security=true; MultipleActiveResultSets = True";
            //strConnection = "Data Source=KENTS-WORK-PC\\CASS_SQLEXPRESS; Initial Catalog=NBFoodPantry;Integrated Security=true; MultipleActiveResultSets = True";

            sqlConn = new SqlConnection(@strConnection);
            try
            {
                sqlConn.Open();
            }
            catch (Exception ex)
            {
                string strMsg;

                WriteErrorLog(strErrorLogFile, "ConnectToDatabase", ex.Message, false);
                strMsg = "ConnectToDatabase: SQL Open failed.  Please make sure that you database ";
                strMsg += "instance and name are correct.  Also make sure that the SQL engine is running.";
                System.Windows.MessageBox.Show(strMsg);
            }
        }
        catch (Exception ex)
        {
            string strMsg;

            WriteErrorLog(strErrorLogFile, "ConnectToDatabase", ex.Message, false);
            strMsg = " ConnectToDatabase: failed with error, " + ex.Message + ".";
            System.Windows.MessageBox.Show(strMsg);
        }

This is what application settings are designed to handle. Under the properties node in your project, open the settings. This has built in support for connection strings:

设置对话框

Then you can access the settings in your code by its name:

Properties.Settings.Default.ConnectionString

All of this is stored in your App.config, which you can modify on various machines to have different values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM