如何获取 app.config 中所有连接字符串的列表

需要创建一个小型控制台应用程序,它需要两个参数:

  1. 文件的文件位置app.config

  2. passkey 我的问题是控制台应用程序需要读取connectionStrings并加密它,然后将加密的文本保存到配置文件中。我已经看过了,但没有找到任何解决方案。

我的app.config文件可能如下所示:

<?xml version="1.0" encoding="utf-8"?>

    <configuration>

     <connectionStrings>

        <add name="Conn1" connectionString="Data Source=Database1;Initial Catalog=DB12;User ID=User1234;Password=Qwerty123" providerName="System.Data.SqlClient" />

        <add name="Conn2" connectionString="Data Source=Database2;Initial Catalog=DB12;User ID=User1234;Password=Qwerty123" providerName="System.Data.SqlClient" />

       </connectionStrings>

      <startup>

        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />

      </startup>

</configuration>

我已经完成了加密部分。我只需要在这个例子中读取这两个connectionstrings并加密它们。请注意,connectStrings每次的名称都不同,因为控制台应用程序是由 TFS 构建服务器触发的。


森栏
浏览 118回答 3
3回答

长风秋雁

基本上,您并不真正需要连接字符串的名称,而是需要连接本身。我相信您只需要foreach遍历它们,并且对于每次迭代,您都可以获得 connectionString 直到 app.config 中的最后一个。&nbsp;foreach (System.Configuration.ConnectionStringSettings css in System.Configuration.ConfigurationManager.ConnectionStrings)&nbsp;{&nbsp; &nbsp;string connectionString = css.ConnectionString;&nbsp;&nbsp;&nbsp; &nbsp;// encryption part&nbsp; &nbsp;// rewriting the connectionString in the app.config or however you want ot be done&nbsp;&nbsp;}你提到你已经完成了加密部分,你需要的只是读取字符串。

慕雪6442864

想出了这个可以与应用程序和网络一起使用的方法,请注意我确实还需要更改值并将它们保存到磁盘,因此不能只是循环var appConfig = System.Web.HttpContext.Current == null&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");var needsToSave = false;foreach (var appCon in appConfig.ConnectionStrings.ConnectionStrings.Cast<ConnectionStringSettings>()){&nbsp; &nbsp; //do stuff}
打开App,查看更多内容
随时随地看视频慕课网APP