シリアライズ可能なオブジェクトのpublicフィールド、もしくはgetとsetの両方が実装されてあるプロパティが対象となります。
using System;
using System.IO;
using System.Xml.Serialization;
///
/// XML形式でのファイルへの保存処理
///
/// フルパス
/// 保存対象
/// エラー内容
/// true = 正常終了 : false = 異常終了
public static bool Save(string path, T obj, out string err)
{
// エラーメッセージの初期化
err = string.Empty;
// 保存先のディレクトリ存在確認(無い場合は作成)
try
{
string dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
}
catch (Exception ex)
{
err = ex.Message;
return false;
}
// 保存処理
bool ret = false;
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
try
{
XmlSerializer xml = new XmlSerializer(typeof(T));
xml.Serialize(fs, obj);
ret = true;
}
catch (Exception ex)
{
err = ex.Message;
ret = false;
}
}
return ret;
}
///
/// XML形式のファイルからの読み込み
///
/// フルパス
/// 展開先
/// エラー内容
/// true = 正常終了 : false = 異常終了
public static bool Load(string path, out T obj, out string err)
{
// エラーメッセージの初期化
err = string.Empty;
// 読み込み先ファイルの存在確認(無い場合は例外発生)
try
{
if (!File.Exists(path))
throw new Exception("無効なパスが指定されました");
}
catch (Exception ex)
{
// 例外が発生したのでfalseを返す
obj = default(T);
err = ex.Message;
return false;
}
// 読み込み処理
bool ret = false;
using (FileStream fs = new FileStream(path, FileMode.Open))
{
try
{
XmlSerializer xml = new XmlSerializer(typeof(T));
obj = (T)(xml.Deserialize(fs));
ret = true;
}
catch (Exception ex)
{
obj = default(T);
err = ex.Message;
}
}
return ret;
}