0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# ファイル保存のためのXMLシリアライズ - はじめのいっぽ

Last updated at Posted at 2016-12-27

やりたかったこと

  • 簡易ログビューワーにて、アプリケーション起動時に前回開いていたファイルを読み込みたい。
  • ファイル名はアプリケーションのプロパティとして扱いたくない。(というか、Windowsに痕跡を残したくない)

独自データはシリアライズを

シリアライズって何となく敷居が高いイメージがありますが、一度手を出せば簡単です。
自分はど忘れしていたので、改めていちからシンプルであろうやり方を行ったのでそのメモです。

ソースコード(※必要な部分のみ抜粋)

using System.IO;
using System.Xml.Serialization;

public class RFile
{
    public string FileName { get; set; }
}
public partial class Form1 : Form
{
    //独自データのファイルは、実行時のフォルダに固定名称で r.xml としておく
    static readonly string fileName = $@"{Application.StartupPath}\r.xml";
    RFile rFile = null;
    
    private void Form1_Load(object sender, EventArgs e)
    {
        if (File.Exists(fileName))
        {
            //独自データ読込
            XmlSerializer s = new XmlSerializer(typeof(RFile));
            StreamReader sr = new StreamReader(fileName, new System.Text.UTF8Encoding(true));
            rFile = (RFile)s.Deserialize(sr);
            sr.Close();
            logReader.ReadStart(rFile.FileName);
        }
        else
            rFile = new RFile();
    }
    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        logReader.ReadStop();

        //独自データ保存
        XmlSerializer s = new XmlSerializer(typeof(RFile));
        StreamWriter sw = new StreamWriter(rFileName, false, new System.Text.UTF8Encoding(true));
        s.Serialize(sw, rFile);
        sw.Close();
    }
}

参考サイト

以上

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?