c# 如何生成dat数据文件

2024-11-30 17:13:05
推荐回答(1个)
回答1:

使用数据库或者文件存储都只是一种方式而已,各有各的好处,根据需求来选择就好了。

生成.dat文件,实际上就是运用C#的序列化方法操作而已。

给你一个例子,就是保存C#的对象成为.dat文件,注意此处保存的是一个Dictionary对象:
public static Dictionary dic_FarmCropsInfo = new Dictionary(); //需要保存的对象

1、读取文件信息
///


/// 获取作物信息
///

public static void GetFarmCropsInfo()
{
try
{
string cropinfo_fn = AppDomain.CurrentDomain.BaseDirectory + "CropsInfo.dat";
using (System.IO.FileStream fs = new System.IO.FileStream(cropinfo_fn, System.IO.FileMode.Open))
{

BinaryFormatter bf = new BinaryFormatter();

dic_FarmCropsInfo = bf.Deserialize(fs) as Dictionary;
}
}
catch { }
}

2、存储文件信息

///
/// 存储作物信息
///

public static void SetFarmCropsInfo()
{
try
{
string cropinfo_fn = AppDomain.CurrentDomain.BaseDirectory + "CropsInfo.dat";
using (System.IO.FileStream fs = new System.IO.FileStream(cropinfo_fn, System.IO.FileMode.OpenOrCreate))
{

BinaryFormatter bf = new BinaryFormatter();

bf.Serialize(fs, dic_FarmCropsInfo);
}
}
catch { }
}