using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
//クラス保存出来るように、属性を追加
[Serializable()]
public class Hoge
{
public DateTime d;
}
public class SaveLoad
{
public const string FILE_NAME = "hoge.txt";
public static void InitFile()
{
if(!File.Exists(FILE_NAME))
{
Hoge[] h = new Hoge[1];
h[0] = new Hoge();
h[0].d = DateTime.Now;
Save(h);
}
}
public static void Save(Hoge[] h)
{
FileStream fs = new FileStream(FILE_NAME,FileMode.Create,FileAccess.Write);
BinaryFormatter b = new BinaryFormatter();
b.Serialize(fs,h);
fs.Close();
}
public static Hoge[] Load()
{
BinaryFormatter b = new BinaryFormatter();
FileStream fs = new FileStream(FILE_NAME, FileMode.OpenOrCreate, FileAccess.Read);
Hoge[] loadFile;
loadFile = (Hoge[])b.Deserialize(fs);
fs.Close();
return loadFile;
}
public static void Main()
{
Hoge[] h;
//ファイルがない場合は、ファイルを作成
SaveLoad.InitFile();
//ファイルのロード
h = SaveLoad.Load();
System.Console.WriteLine("前回起動時刻は"+ h[0].d.ToString("yyyy/MM/dd HH:mm:ss")+"です。");
//終了時刻をセーブ
h[0].d = DateTime.Now;
SaveLoad.Save(h);
}
2016年6月11日土曜日
.net シリアライズ機能を使用してクラスの保存
シリアライズ機能を使用する時のひな型
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿