C# WinForm application - How to save connection string (SQLite)

有些话、适合烂在心里 提交于 2019-12-06 21:50:38

I think what you want to do is use Settings (instead of using the app.config). See this: https://msdn.microsoft.com/en-us/library/aa730869%28v=vs.80%29.aspx

It's basically the same as the config file, but gives the user (and you) easy access.

First set a default connection string in the designer:

Then access it like textBox1.Text = Properties.Settings.Default.connectionString;

Do the reverse to save it: Properties.Settings.Default.connectionString = textBox1.Text;

And make sure you save: Properties.Settings.Default.Save();

You should make use of special folders. Either LocalApplicationData (applies to current user - local only) or ApplicationData (applies to current user - roaming):

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

This is where you should store path \ connection string to the db file selected by user. These folders are created for all user profiles on Windows OS. For example, if your logon name is "Hari" then the path would be "C:\Users\Hari\AppData\Local". Hari has full access to this path so he can write to it.

Also, this allows multiple users to use your software. They won't step on each other. All of them will have their own DB files. If this is not what you desire, then you may use other special folders (like CommonApplicationData) mentioned here:

https://msdn.microsoft.com/en-us/library/system.environment.specialfolder%28v=vs.110%29.aspx

However to use some of them you may have to have admin rights. (For the two special folders I described above, you don't need admin rights.) In that case you could ask for DB file path at the installation time.

João Miguel Brandão

This could help:

private static void UpdateSetting(string key, string value)
{
    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save();

    ConfigurationManager.RefreshSection("appSettings");
}

From: App.Config change value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!