yazdığım,derlediğim işe yarar statik method,fonksiyonları paylaşıyorum.bir yerden başlamak lazım.
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration; // gerekmeyebilir
yoksa ekliyoruz.
// appSettings e erişim
public static string GetAppKey(string key) // varsa değeri yoksa null döndürür
{
return WebConfigurationManager.AppSettings[key];
}
public static int GetKeyInt(string key) // varsa değeri yoksa 0 döndürür
{
int result;
Int32.TryParse(WebConfigurationManager.AppSettings[key], out result);
return result;
}
public static bool GetKeyBool(string key) // True/False değer kontrolü yapar.
{
bool sonuc;
bool.TryParse(GetAppKey(key),out sonuc);
return sonuc;
}
// düzenleme
public static bool SetAppValue(string anahtar, string deger) // ayar varsa günceller yoksa ekler :=)
{
try
{
Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
if (GetAppKey(anahtar) == null)
{
appSettingsSection.Settings.Add(anahtar, deger);
configuration.Save();
}
else
{
appSettingsSection.Settings[anahtar].Value = deger;
configuration.Save();
}
return true;
}
catch
{
return false;
}
}
// kaldırma
public static bool RemoveAppKey(string key) // keyi web.config den kaldırır
{
try
{
Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
if (GetAppKey(key) != null)
{
appSettingsSection.Settings.Remove(key);
configuration.Save();
}
return true;
}
catch
{
return false;
}
}
Tags: appSettings