我有一個應用程序需要檢查數據庫是否存在特定的代碼;如果它確實存在,則必須加載該代碼的相應值,否則返回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幫助
'對象引用是'的NullReferenceException ';沒有任何對象可以使用。 – Brian 2013-02-28 18:37:30
我不得不問你爲什麼試圖在app.config中做這件事,而不是DB – ChrisBint 2013-02-28 18:38:02
'key'沒有在你的設置中定義。使用你的調試器來找出原因。 – 2013-02-28 18:39:13