1

特定のコードが存在するかどうかをデータベースに確認する必要があるアプリケーションがあります。存在する場合は、そのコードの対応する値をロードする必要があります。それ以外の場合は 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();

エラー: オブジェクト参照がオブジェクトのインスタンスに設定されていません。

助けてください

4

3 に答える 3

2

値が null でないことを確認してください。これを試して:

if (config.AppSettings.Settings.ContainsKey(key) && 
    config.AppSettings.Settings[key] != null)
{
    return config.AppSettings.Settings[key].ToString();
}
于 2013-02-28T19:08:10.377 に答える
1

ほとんどの場合、存在しない設定にアクセスしようとしています。その例外を catch ブロックで処理し、その場合は null を返すことができます。

于 2013-02-28T18:41:03.090 に答える