且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#WinForm应用程序-如何保存连接字符串(SQLite)

更新时间:2023-02-17 08:16:35

我认为您要使用的是设置(而不是使用app.config)。请参阅: https://msdn.microsoft .com / en-us / library / aa730869%28v = vs.80%29.aspx



它与配置文件基本相同,但是给出了用户(和您)轻松访问。



首先在设计器中设置默认的连接字符串:

然后像 textBox1.Text = Properties.Settings.Default.connectionString;



执行相反的操作以保存它: Properties.Settings.Default.connectionString = textBox1.Text;



并确保保存: Properties.Settings.Default.Save();


I have a winform app in .NET 4.0 with database (SQLite). I need to add an option for user to be able to change the path to the file containing the database - in short, to change the connection string. I used app.config to save connection string like this:

<connectionStrings>
<add name="connectionString" connectionString="Data Source=D:\myDatabase.db; FailIfMissing=True; Version=3"/>
</connectionStrings>

Is there a way to allow user to modify app.config file (it is located in Program Files folder)? I do not want to run the app as an administrator, is there a way to give administrator rights to user temporarely, only when trying to modify app.config file?

If you have any better suggestion for persistently storing connection string, please share.

Thank you!

EDIT: I can actually change app.config file:

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["connectionString"].ConnectionString = "Data Source=" + path + "; FailIfMissing=True; Version=3";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");

Problem is when user is not an administrator, access to the file is denied. Is there a workaround (I do not want to run the app as administrator)? Or is there a better way to store my connection string?

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();