c# - 写入和读取应用程序配置设置

标签 c#

我有一个应用程序需要检查数据库是否存在特定代码;如果确实存在,则必须加载该代码的相应值,否则返回 null。

我不想为每个代码访问数据库(运行大约 200.000 个代码)。

所以我得到了这个小应用程序来测试 app.conf

public static void setAppSetting(string key, string value)
{
   Configuration config =  ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);

   if (config.AppSettings.Settings != null)
   {            
      config.AppSettings.Settings.Remove(key);
   }

   config.AppSettings.Settings.Add(key, value);
   config.Save(ConfigurationSaveMode.Modified);
 }

public static string getAppSetting(string key)
{
   try
   {
      Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);
      return config.AppSettings.Settings[key].ToString();
   }

   catch (Exception ex)
   {
      throw ex;
   }
}

private static void loadKeysValues()
{
   using (SqlConnection Gcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
   {
      //Open Connection
      Gcon.Open();
      using (SqlCommand sqlCmd = new SqlCommand("SELECT key,value FROM tables", Gcon))
      {
         using (SqlDataReader reader = sqlCmd.ExecuteReader())
         {
            if (reader.HasRows)
            {
               while (reader.Read())
               {
                  System.Console.WriteLine(reader.GetString(0) + " , " + reader.GetString(1));
                  setAppSetting(reader.GetString(0), reader.GetString(1));
               }
            }
         } // End of SqlDataReader

      } // end of SqlCommand
    }
  }

static void Main(string[] args)
{
   System.Console.WriteLine("Loading.........");
   loadKeysValues();
   System.Console.WriteLine("Completed");
   System.Console.WriteLine("Input a key to get its value");
   var input = System.Console.Read().ToString();
   System.Console.WriteLine(getAppSetting(input));
   System.Console.ReadLine();
}

但是我在这一行的 getAppSetting() 中遇到错误:

return config.AppSettings.Settings[key].ToString();

错误:未将对象引用设置为对象的实例。

请帮忙

最佳答案

确保该值不为空。 试试这个:

if (config.AppSettings.Settings.ContainsKey(key) && 
    config.AppSettings.Settings[key] != null)
{
    return config.AppSettings.Settings[key].ToString();
}

关于c# - 写入和读取应用程序配置设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15143057/

相关文章:

c# - 如何在MvvmCross中退订弱订阅

c# - 在 "object not set"错误之前捕获不存在的 XML 节点

c# - 更新包后,未将对象引用设置为 _Layout.cshtml 中的对象实例

c# - 如何在将 XPS 转换为 PDF 时获取 GhostPDL 进度通知?

c# - 使用正则表达式过滤掉不良字符

c# - 奇怪的 xml c# 问题,Vista 是否缓存程序文件?

c# - Azure WebJobs 和 ServiceBusTrigger

c# - .net core 中的默认最大请求长度是多少

c# - 当只允许该程序的一个实例时从系统托盘恢复窗口

c# - WCF websocket 在断开连接时不会关闭