除数据库外的数据保存在文件中

时间:2017-03-16 12:29:43

标签: c#

我是Windows表单应用程序的新手我想在文件中保存数据,除了(Sql)或数据库。我尝试了很多东西,我只能在文本文件中存储一个值

TextWriter txt = new System.IO.StreamWriter("E:\\Tahir\\ScaleSystemDataSave\\First.txt");
txt.Write(txtFirsrWeight.Text);
txt.Close();

但我想在文件中存储一个对象我该怎么做呢我的对象是这样的

private void btnSave_Click(object sender, EventArgs e)
{
    FirstTime obj = new FirstTime();
    obj.CardNo = txtCardNo.Text;
    obj.DateTime = txtDateTimePicker.Value;
    obj.VehicleNo = txtVehicalNo.Text;
    obj.WeightType = Convert.ToString(cbxWeigtType.SelectedItem);
    obj.FirstWeight = txtFirsrWeight.Text;
    if (rbtWithDriver.Checked == true)
    {
        obj.IsDriver = (int)Status.WithDriver;
    }
    else if (rbtWithouDriver.Checked == true)
    {
        obj.IsDriver = (int)Status.withOutDriver;
    }

}

1 个答案:

答案 0 :(得分:1)

您有两种选择。

  1. 像逗号分隔文件一样自己格式化文本文件,然后重新读取文件,解析它并将值分配回对象。

  2. 使用已知的序列化技术,例如XML或JSON。

  3. 以下是实现所需内容的JSON序列化示例。

    var first = new FirstTime()
                {
                    CardNo = "121515611",
                    Date = DateTime.Now.Date,
                    VehicleNo = "MNRG23434",
                    WeightType = "MyWeight",
                    FirstWeight = "FirstWeight"
                };
    
                var fileText = JsonConvert.SerializeObject(first);
    
                TextWriter txt = new StreamWriter("C:\\First.txt");
                txt.Write(fileText);
                txt.Close();
    
                var fileStream = File.Open("C:\\First.txt",FileMode.Open);
    
                var fileReader = new StreamReader(fileStream);
                var contents = fileReader.ReadToEnd();
    
                var restoredObject = JsonConvert.DeserializeObject<FirstTime>(contents);
    

    这将按照以下格式存储数据

    {"CardNo":"121515611","Date":"2017-03-16T00:00:00+00:00","VehicleNo":"MNRG23434","WeightType":"MyWeight","FirstWeight":"FirstWeight"}
    

    希望对你有所帮助。