当前位置: 首页 > 编程语言 > C#

来自自定义文件共享的AppSettings

时间:2023-04-11 03:06:29 C#

来自自定义文件的AppSettings我正在尝试使用.NET2.0中的配置和设置类我知道如果以下内容包含在名为app.config的文件中,我可以通过以下方式访问appSetting//这将返回“HelloWorld!”ConfigurationManager.AppSettings["Foo"]但是,如果文件名为app1.config(或任何其他名称),则无法访问appSetting。据我了解,使用ConfigurationManager.OpenExeConfiguration我应该阅读自定义配置设置文件。配置conf=ConfigurationManager.OpenExeConfiguration(@"...app1.config");//这会打印一个空字符串。Console.WriteLine(conf.AppSettings.Settings["Foo"]);但是conf.AppSettings.Settings["Foo"]返回一个空字符串。我也尝试了以下代码但没有成功ExeConfigurationFileMapexeFileMap=newExeConfigurationFileMap();exeFileMap.ExeConfigFilename=System.IO.Directory.GetCurrentDirectory()+"\App1.config";配置myConf=ConfigurationManager.OpenMappedExeConfiguration(exeFileMap,ConfigurationUserLevel.None);//也返回空字符串Console.WriteLine(myConf.AppSettings.Settings["Foo"]);如何从一个不叫app.config的文件中读取设置?我创建了自定义文件myCustomConfiguration并将其属性“复制到输出目录”更改为true在CS文件中staticvoidMain(string[]args){字典dictionary=GetNameValueCollectionSection("appSettings",filePath);//为了让你的钥匙做dictionary["Foo"]Console.WriteLine(dictionary["Foo"]);控制台.ReadLine();}privatestaticDictionaryGetNameValueCollectionSection(stringsection,stringfilePath){varxDoc=newXmlDocument();varnameValueColl=新词典nary();varconfigFileMap=newExeConfigurationFileMap{ExeConfigFilename=filePath};配置config=ConfigurationManager.OpenMappedExeConfiguration(configFileMap,ConfigurationUserLevel.None);字符串xml=config.GetSection(section).SectionInformation.GetRawX();xDocml.LoadXml(xml);XmlNodexList=xDoc.ChildNodes[0];foreach(XmlNodexNodoinxList.Cast().Where(xNodo=>xNodo.Attributes!=null)){nameValueColl.Add(xNodo.Attributes[0].Value,xNodo.Attributes[1].Value);}返回nameValueColl;虽然这行得通,但我也在寻找更好的方法你应该使用设置文件,使用、保存和加载方法更方便,你可以随心所欲地命名。例如。我的Settings-File名为“EditorSettings.settings”,我访问它的属性如下:以上是C#学习教程:AppSettings分享自CustomFiles的所有内容,如果对大家有用需要进一步了解C#学习教程,希望大家多多关注——MyNamespace.MyProject.EditorSettings.Default.MyProperty1本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: