为什么我的连接字符串只能在 Dev 中工作?

Why is my Connection String only working in Dev?

请参阅下面的 DGibbs 回答。

我无法将配置文件与 EXE 一起保存,因为它存在于每个用户的桌面上,所以我似乎无法将密码存储在配置文件中,必须想出其他一些解决方案。


我有一个应用程序需要 运行 以管理员身份执行 CMD 命令。为此,我将密码存储在 app.config:

的连接字符串中
<connectionStrings>
  <add name="mypw" connectionString="PASSWORD" />
</connectionStrings>

然后我可以在我的 Cmd class 中将其作为 SecureString 调用:

    private static SecureString pw()
            {
                string connectionString = ConfigurationManager.ConnectionStrings["mypw"].ConnectionString;
                SecureString ss = new SecureString();

                foreach (char c  in connectionString)
                {
                    ss.AppendChar(c);
                }

                return ss;
            }

当我 运行 在我的机器上调试 (F5) 的 VS 应用程序时,它工作正常并且密码被检索。然而,当 运行 在开发环境中使用它时,我看到了异常 Object Reference not set to an instance of an object,并且从我自己的调试中我可以看到这是在这一行发生的:

string connectionString = ConfigurationManager.ConnectionStrings["mypw"].ConnectionString;

任何人都可以解释为什么应用程序能够在我的机器上检索连接字符串,但部署在其他地方时却不能?发布应用程序时 app.config 文件是否发生变化?

一些东西,不要使用<connectionStrings>,这通常用于存储数据库连接的凭据,在这里没有意义。尝试在 App.config 文件中使用 AppSettings,例如

<appSettings>
    <add key="mypw" value="password" />
</appSettings>

您可以像这样检索值:

string pw = ConfigurationSettings.AppSettings["mypw"];

最后,确保您已部署配置文件,它应该是 [ApplicationName].exe.config 不是 App.Config。如果没有出现,请检查 Copy to output directory 设置,确保它设置为 Copy Always.