这两天开了博客,觉得有必要写点什么东西充实一下,一来很多资料都不在电脑,二来也是为以后工作方便写一下记录。
这是之前兼职写的一个液压机控制软件中的文件保存操作,采用json语言保存数据,特别方便,包括单个类型变量、数组等的保存和读取。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApplication1
{
class Syscfg
{
public int IsSaved = 1;
public double intpama = 1.2;
public double doublepama = 2.3;
public double[] buf = { 1, 2, 3 };
//public double[] doublebuf = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
private Syscfg()
{
}
public static Syscfg config = new Syscfg();
}
}
下面是对文件操作的一些方式,包括数据文件读取:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Globalization;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace WpfApplication1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
try
{
StreamReader sr1 = new StreamReader("syscfg.ini", Encoding.Default);
string jsons1 = sr1.ReadToEnd();
Syscfg tmp_cfg1 = JsonConvert.DeserializeObject<Syscfg>(jsons1);
sr1.Close();
tmp_cfg1.IsSaved = Syscfg.config.IsSaved;
}
catch
{
using (StreamWriter sw = new StreamWriter("syscfg.ini", false))
{
string json_out = JsonConvert.SerializeObject(Syscfg.config);
sw.Write(json_out);
sw.Close();
}
}
StreamReader sr = new StreamReader("syscfg.ini", Encoding.Default);
string jsons = sr.ReadToEnd();
Syscfg tmp_cfg = JsonConvert.DeserializeObject<Syscfg>(jsons);
sr.Close();
tmp_cfg.intpama = 222;
tmp_cfg.doublepama = 333;
tmp_cfg.buf[0] = 1.1;
tmp_cfg.buf[1] = 2.2;
tmp_cfg.buf[2] = 3.3;
using (StreamWriter sw = new StreamWriter("syscfg.ini", false))
{
string json_out = JsonConvert.SerializeObject(tmp_cfg);
sw.Write(json_out);
sw.Close();
}
}
}
}