2013-02-28 107 views
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(); 

錯誤:對象引用未設置到一個對象的一個​​實例。

Plz幫助

+1

'對象引用是'的NullReferenceException ';沒有任何對象可以使用。 – Brian 2013-02-28 18:37:30

+1

我不得不問你爲什麼試圖在app.config中做這件事,而不是DB – ChrisBint 2013-02-28 18:38:02

+1

'key'沒有在你的設置中定義。使用你的調試器來找出原因。 – 2013-02-28 18:39:13

回答

1

很可能您嘗試訪問不存在的設置。你可以在你的catch塊中處理這個異常,並在這種情況下返回null。

+1

好吧會檢查一個 – Jmocke 2013-02-28 18:47:22

+2

我不認爲這是一個好主意,在catch塊中處理這個問題,而你可以檢查null的值爲user42暗示 – khlr 2013-02-28 19:20:20

2

確保該值不爲空。 試試這個:

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

ToString()方法返回鴕鳥政策的價值,與Value屬性嘗試:未設置爲一個object.`的實例

return config.AppSettings.Settings[key].Value; 
相關問題