使用AppSetting读取配置文件

时间:2017-06-16 11:07:57

标签: c# config configuration-files configurationmanager

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

存储配置文件(完美无瑕):

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");
    }
}

2 个答案:

答案 0 :(得分:1)

作为转化,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);

答案 1 :(得分:1)

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();