2017-06-29 48 views
0

類我有我的應用程序的所有參數的配置類,從掃描儀獲取圖像。
我有喜歡的顏色/ BW,分辨率...
的參數經常更改的參數,所以我在尋找,當我保存的參數改變的參數在app.config文件的解決方案自動寫入。爲了完成恢復的事情,請在軟件初始化時從app.config編寫我的類。 這裏是我的兩個類:C#參數用的app.config

private void GetParameters() { 
     try 
     { 
      var appSettings = ConfigurationManager.AppSettings; 
      Console.WriteLine(ConfigurationManager.AppSettings["MyKey"]); 

      if (appSettings.Count == 0) 
      { 
       Console.WriteLine("AppSettings is empty."); 
      } 
      else 
      { 
       foreach (var key in appSettings.AllKeys) 
       { 
        Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]); 
       } 
      } 
     } 
     catch (ConfigurationErrorsException) 
     { 
      MessageBox.Show("Error reading app settings"); 
     } 
    } 
    private void SetParameters(string key, string value) 
    { 
     try 
     { 
      Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
      KeyValueConfigurationCollection confCollection = configManager.AppSettings.Settings; 
      if (confCollection[key] == null) 
      { 
       confCollection.Add(key, value); 
      } 
      else 
      { 
       confCollection[key].Value = value; 
      } 
      configManager.Save(ConfigurationSaveMode.Modified); 
      ConfigurationManager.RefreshSection(configManager.AppSettings.SectionInformation.Name); 
     } 
     catch (ConfigurationErrorsException) 
     { 

      MessageBox.Show("Error writing app settings"); 
     } 

    } 

我不想調用的方法每一個參數...
還有就是我的參數類:

class ScannerParameters 
{ 
    public bool Color { get; set; } 

    public int Resolution{ get; set; } 

    public string FilePath { get; set; } 

    public TypeScan TypeScan { get; set; } 

    public string TextTest{ get; set; } 

} 
+0

所以你的意思是,如果有人改變了你的應用程序中的參數,你希望這些值保存回配置? –

+0

這就是我正在搜索的行爲。 – betsou

+0

它只是不工作?你真的不說,麻煩的是什麼,所以這是一個有點不清楚你需要什麼.. –

回答

1

的問題可以被翻譯into 如何將對象保存爲某種持久性?

可以使用數據庫(看起來像是一種矯枉過正),也可以使用序列化器對其進行序列化,或者直接將其全部寫入文本文件中。使用json序列化,將您的ScannerParameters序列化,然後將其寫入文件似乎是最合適的。

使用newtonsoft JSON,這是事實上的標準,.NET有很好的例子@http://www.newtonsoft.com/json/help/html/SerializingJSON.htm

在你的情況,你會怎麼做:

// our dummy scannerParameters objects 
var parameters = new ScannerParameters(); 

// let's serialize it all into one string 
string output = JsonConvert.SerializeObject(paramaters); 

// let's write all that into a settings text file 
System.IO.File.WriteAllText("parameters.txt", output); 

// let's read the file next time we need it 
string parametersJson = System.IO.File.ReadAllText("parameters.txt); 

// let's deserialize the parametersJson 
ScannerParameters scannerParameters = JsonConvert.DeserializeObject<ScannerParameters>(parametersJson); 
+1

爲什麼'.txt'文件,而不是一個'.json'文件? – maccettura

+1

該參數是一個路徑,畢竟json只是文本。 'file.json'似乎比'file.txt'更可怕。我想這只是我個人的偏好。儘管調用'file.json'這個東西的確是更具描述性的。 – pijemcolu

+0

謝謝,那是我使用的解決方案。 如何將其反序列化爲ScannerParameters類? – betsou