使用 AppSetting 读取配置文件

Read Config File using AppSetting

我已使用 ConfigurationManager Class 将我的应用程序设置存储在配置文件中,我的配置文件位于自定义路径中,现在我想读取我的配置文件,但我的代码无法正常工作。我应该如何更改我的代码?

存储配置文件(完美运行):

static void AddUpdateAppSettings2(string key, string value)
{
    try
    {
        string _path = Application.StartupPath + "\ss.ini";
        ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap()
        {
            ExeConfigFilename = _path
        };
        Configuration configFile = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

读取配置文件(不工作,只有当我的配置文件存储是默认路径时才工作):

static void ReadSetting(string key)
{
    try
    {
        var appSettings =ConfigurationManager.AppSettings;
        string result = appSettings[key] ?? "Not Found";
        Console.WriteLine(result);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error reading app settings");
    }
}

作为转换,app.config 文件始终存储在名称为 application_name.config 的应用程序路径中。

如果您想将配置存储在自定义路径中,请考虑使用单独的 XML 文件绕过 app.config 文件。以下是示例代码:

internal sealed class AppSettingsSerializer
{
    private AppSettingsSerializer() { }

    static int BufferSize { get { return 4096; } }

    internal static AppSettings GetAppSettings(string filePath)
    {
        if(File.Exists(filePath) == false)
            return new AppSettings();

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(AppSettings));
        using(FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, BufferSize, FileOptions.SequentialScan))
        {
            XmlReader xmlReader = XmlReader.Create(fileStream);
            return (AppSettings)xmlSerializer.Deserialize(xmlReader);
        }
    }

    internal static void SetAppSettings(string filePath, AppSettings appSettings)
    {
        XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();
        xmlSerializerNamespaces.Add("", "");

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(AppSettings));
        using(FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, BufferSize, FileOptions.WriteThrough))
        {
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
            xmlWriterSettings.Indent = true;
            xmlWriterSettings.NewLineOnAttributes = true;

            XmlWriter xmlWriter = XmlWriter.Create(fileStream, xmlWriterSettings);
            xmlSerializer.Serialize(xmlWriter, appSettings, xmlSerializerNamespaces);
        }
    }
}

public sealed class AppSettings
{
    public bool Setting1 { get; set; }
    public string Setting2 { get; set; }

    public AppSettings()
    {
        Setting1 = false;
        Setting2 = "localhost";
    }
}

用法如下:

AppSettings appSettings = appSettings = AppSettingsSerializer.GetAppSettings(appSettingsFilePath);
AppSettingsSerializer.SetAppSettings(appSettingsFilePath, appSettings);
web.config 

<configuration>
  <appSettings>
 <add key="ConnectionString" value="your connectionstring"/>
  </appSettings>
</configuration>

.cs file

 string connectionstring= ConfigurationManager.AppSettings["your connectionstring name is called in web.config"].ToString();