using System.Configuration; using System.IO; using System.Reflection; namespace ShrlAlgoToolkit.Core.Assists { public class ConfigAssist { /// /// 获取项目文件夹下的配置文件根据Key获取Value /// /// 键 /// public static string GetCfgValue(string key) { var assembly = Assembly.GetCallingAssembly(); var uri = new Uri(Path.GetDirectoryName(assembly.Location) ?? string.Empty); var map = new ExeConfigurationFileMap { ExeConfigFilename = Path.Combine(uri.LocalPath, assembly.GetName().Name + ".dll.config") }; var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); var loadpath = config.AppSettings.Settings[key].Value; //若路径存在则自动获取该路径 return loadpath; } /// /// 保存到程序目录下的配置文件 /// /// 键 /// 值 public static void SetCfgPairs(string key, string value) { var assembly = Assembly.GetCallingAssembly(); var uri = new Uri(Path.GetDirectoryName(assembly.Location) ?? string.Empty); var map = new ExeConfigurationFileMap { ExeConfigFilename = Path.Combine(uri.LocalPath, assembly.GetName().Name + ".dll.config") }; var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); config.AppSettings.Settings[key].Value = value; //将用户选取的路径_path赋给app.config中的_path(名称自取) //ConfigurationManager.OpenMappedExeConfiguration(map, 0).AppSettings.Settings["FamilyPath"].Value = SelectedPath; config.AppSettings.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Modified); //将配置保存 ConfigurationManager.RefreshSection("appSettings"); //刷新配置文件 //if (Directory.Exists(config.AppSettings.Settings["FamilyPath"].Value))//判断配置的路径是否存在 //{ // dialog.SelectedPath = config.AppSettings.Settings["FamilyPath"].Value;//若路径存在则自动获取该路径 //} } } }