如何在 .net 6 winform 中创建连接字符串

问题描述 投票:0回答:1

我在 .net 6 c# 中创建了 winform,但我没有在解决方案中找到任何 App.json 或 appsetting.json。 任何人都可以帮我添加连接字符串吗?

如果我从另一个项目复制 appsetting.json 文件,它应该有效吗?

c# .net winforms connection-string
1个回答
2
投票

在 Winforms 应用程序中,配置数据存储在 app.config 文件中。当您在 YourAppName.exe.config 中构建应用程序时,此文件会被重命名,并且应与您的应用程序一起分发。

所以你需要通过以下方式将应用程序配置文件添加到你的项目中

Project => Add => New Item => Application Configuration File.

现在您的项目根目录中有一个名为 app.config 的 XML 文件,您可以编辑它向一些预定义的部分添加值:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="Title" value="MyApp"/>
    </appSettings>
    <connectionStrings>
        <add name="MyConn" connectionString="server=localhost;database=MyAppDb;Trusted_Connection=Yes"/>
    </connectionStrings>
</configuration>

接下来,您可以像这样在 winforms 应用程序中使用这些信息:

private void Form1_Load(object sender, EventArgs e)
{
    this.Text = ConfigurationManager.AppSettings["Title"];
    string constr = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
    Label l = new Label();  
    l.Text = constr;
    this.Controls.Add(l);
}

这里有一篇很老的帖子很好地解释了这个系统。不确定它是否仍然完全适用于 Net6 中的 Winforms 但可能值得一读

© www.soinside.com 2019 - 2024. All rights reserved.