2012-07-19 179 views
1

如果是,那麼我們可以在app.config文件中保存數據或一些文本 然後它是持久性還是臨時性的?C#app.config讀取和寫入

例如,如果我在App.config文件中存儲上次訪問日期時間,然後關閉/在開始我的應用程序一段時間/天/年後關閉應用程序,可能是我可以檢索的上次訪問日期時間。如果是,那麼如何請解釋代碼....

感謝, 拉吉

這裏是我的代碼..

正在嘗試從配置文件.. 日期時間,但顯示錯誤對象不設置爲一個對象像...

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 

if (email.To.Contains(Email) && DateTime.Compare(email.UtcDateTime.Date, Convert.ToDateTime(config.AppSettings.Settings["ModificationDate"].Value)) > 0) 

在這裏,我存儲/保存在app.config文件的日期時間。

System.Configuration.Configuration config = 
      ConfigurationManager.OpenExeConfiguration 
         (ConfigurationUserLevel.None); 

// Add an Application Setting. 
config.AppSettings.Settings.Add("ModificationDate", DateTime.Now + " "); 

// Save the changes in App.config file. 
config.Save(ConfigurationSaveMode.Modified); 

// Force a reload of a changed section. 
ConfigurationManager.RefreshSection("appSettings"); 

Console.WriteLine("Last Update :"+config.AppSettings.Settings["ModificationDate"].Value); 
Console.ReadLine(); 

請建議我爲什麼告訴我該對象未設置我做過任何錯誤,請ANS錯誤...

+0

這不是暫時的,你可以繼續。但這不是處理您的要求的正確方法 – nawfal 2012-07-19 12:40:47

回答

1

您可以創建一個設置xml文件來執行此操作。

在VS去你的項目屬性 - >Settings,然後寫一個值

在代碼中,你可以獲取/設置使用

Properties.Settings.Default.YourVariable = 0; 

如果要設置的值使該值一定要保存它

Properties.Settings.Default.Save(); 

請參閱here一個很好的教程。

-1

你可以使用App.config存儲像任何其他文件,它會持續存在,可下一次你運行你的程序。一般來說,這就是文件存儲的本質。我建議你將這些數據存儲在一個單獨的文件或數據庫中。然而,我不會爲你寫代碼。

0

我會使用自定義配置部分來創建您的配置類型 - 上次訪問日期時間。您可以創建更復雜的層次配置並進行強類型化。

同樣,它取決於您的要求和設計,如果你需要這樣做。否則,標準文件存儲(txt/xml)也可以讓你這樣做。我個人通常使用app.config爲應用程序特定級別(外觀/字體/服務器名等)配置,而不是事務配置。

爲e.g

public class LastAccessConfigurationSection : System.Configuration.ConfigurationSection { 
    [ConfigurationProperty("LastAccess")] 
    public string LastAccess{ 
     get { return (string)this["LaunchTime"]; } 
     set { this["LaunchTime"] = value; } 
    } 
} 

你可以有一個靜態類管理的生命週期,它會讓你堅持的變化。

public static LastAccessConfigurationSection Config { get; internal set; } 

    public static void Initialize() { 
     Config = ConfigurationManager.GetSection("LastAccess") as LastAccessConfigurationSection; 
    }