onsen code monkey

個人的な日記とプログラミング備忘録です

【C#】分離ストレージにXMLファイルを作成する

昔書いたプログラム漁ってたら何かに使えそうなものが出てきたので記録しておく。
Button1で分離ストレージにXMLファイルを作成し、Button2でそれを読み込んだ後消している模様。
System.Xml.Linqを使っている。

using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Xml.Linq;

namespace XMLtoISF
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        string fileName = "";

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            Guid g = System.Guid.NewGuid();
            fileName = g.ToString("N").Substring(0, 8) + ".xml";
            double val = 0.01;
            string str = val.ToString();

            XDocument xml = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),
            new XElement("Employee",
            new XElement("FirstName", "田中"),
            new XElement("LastName", "太郎"),
            new XElement("ID", "999")
            ));

            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly())
            {
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.CreateNew, isf))
                {
                    xml.Save(stream);
                }
            }
        }
        private void Button2_Click(object sender, RoutedEventArgs e)
        {
            XDocument xdoc = null;
            
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly())
            {
                if (isf.FileExists(fileName))
                {
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Open, isf))
                    {
                        xdoc = XDocument.Load(stream);
                    }

                    Console.WriteLine(xdoc.Element("Employee").Element("FirstName").Value);
                    Console.WriteLine(xdoc.Element("Employee").Element("ID").Value);
                }
                isf.DeleteFile(fileName);
            }
        }
    }
}