ファイル入出力
- XMLシリアライズによるファイル入出力
任意のクラスのインスタンスをXMLファイルに入出力します。
// FileText.xmlというファイルにUTF-8エンコーディングで入出力
string szPath = "FileXml.xml";
System.Text.Encoding enc = System.Text.Encoding.UTF8;
SampleObject target = new SampleObject();
//--------------------------------------------
// 書き込み
System.IO.TextWriter textWriter = null;
try
{
textWriter = new System.IO.StreamWriter( szPath, false, enc );
System.Xml.Serialization.XmlSerializer xmlSerializer
= new System.Xml.Serialization.XmlSerializer( target.GetType() );
xmlSerializer.Serialize( textWriter, target );
}
catch( Exception ex )
{
Console.WriteLine( ex.Message );
}
finally
{
if( textWriter != null ) textWriter.Close();
}
//--------------------------------------------
// 読み取り
target = null;
System.IO.TextReader textReader = null;
try
{
textReader = new System.IO.StreamReader( szPath, enc );
System.Xml.Serialization.XmlSerializer xmlSerializer
= new System.Xml.Serialization.XmlSerializer( target.GetType() );
target = ( SampleObject )xmlSerializer.Deserialize( textReader );
}
catch( Exception ex )
{
Console.WriteLine( ex.Message );
}
finally
{
if( textReader != null ) textReader.Close();
}