2017-06-29 50 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