我遇到了一些有趣的事情.我正在尝试为我们的客户制作一个快速控制台应用程序来运行以更改某些程序上的某些连接字符串.这对客户来说是一个“快速应用程序”,我希望它是“白痴证明”.
该应用程序的主要功能之一是重新创建默认配置文件,如果找不到它.
if (!File.Exists("./App.config")) { Console.WriteLine("Config file is missing. Creating a new one Now.."); //file doesn't exist,let's create one. var doc = new XDocument( new XDeclaration("1.0","UTF-16",null),new XElement("configuration",new XElement("startup",new XElement("supportedRuntime",new XAttribute("version","v4.0"),new XAttribute("sku",".NETFramework,Version=v4.5"))),new XElement("appSettings",new XElement("add",new XAttribute("key","targetDatabaseName"),new XAttribute("value","")),"applicationServer"),"sqlServer"),"applicationServerPort"),"customSearchPath"),""))))); using (var sw = new StringWriter()) { using (var xw = XmlWriter.Create(sw)) { doc.Save(xw); xw.Close(); } doc.Save("./App.config"); sw.Close(); } }
在测试时,我注意到如果删除原始App.config文件并使用该应用程序重新创建,则所有ConfigurationManager.AppSettings行都将停止正常运行.即使我手动更改重新创建的配置文件中的值,它们也始终为每个键返回空值.
编辑
我添加了我用来从下面的配置文件中获取值的代码,以及我的应用程序创建的当前配置文件.
_targetDatabaseName = ConfigurationManager.AppSettings["targetDatabaseName"]; _applicationServer = ConfigurationManager.AppSettings["applicationServer"]; _sqlServer = ConfigurationManager.AppSettings["sqlServer"]; _applicationServerPort = ConfigurationManager.AppSettings["applicationServerPort"]; var emptyKeys = new List<string>(); if (string.IsNullOrEmpty(_targetDatabaseName)) emptyKeys.Add("targetDatabaseName"); if(string.IsNullOrEmpty(_applicationServer)) emptyKeys.Add("applicationServer"); if(string.IsNullOrEmpty(_sqlServer)) emptyKeys.Add("sqlServer"); if(string.IsNullOrEmpty(_applicationServerPort)) emptyKeys.Add("applicationServerPort"); if (emptyKeys.Count > 0) { Console.WriteLine("You are missing one of the following required keys " + string.Join(",",emptyKeys) +". Press" + " a key to exit the application."); Console.ReadKey(); Environment.Exit(0); }
这是当前配置文件以及实际值
<?xml version="1.0" encoding="utf-16"?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <appSettings> <add key="targetDatabaseName" value="" /> <add key="applicationServer" value="" /> <add key="sqlServer" value="" /> <add key="applicationServerPort" value="" /> <add key="customSearchPath" value="" /> </appSettings> </configuration>
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。