0

XML ファイルを処理する必要があります (OpenFileDialog [コードはここにはありません] を使用してファイルを選択しています。2 番目のボタンをクリックすると、XML が処理されて、他のファイルに保存する必要があるその XML のツリー構造が表示されます) . しかし、 SaveFileDialog を使用すると、まだ存在しないファイルのファイル名を入力したい。存在しないファイル名を入力すると、空のファイルが作成されます。

       private void button2_Click(object sender, EventArgs e)
        {
        SaveFileDialog fDialog = new SaveFileDialog();
        fDialog.Title = "Save XML File";
        fDialog.FileName = "drzewo.xml";
        fDialog.CheckFileExists = false;
        fDialog.InitialDirectory = @"C:\Users\Piotrek\Desktop";

        if (fDialog.ShowDialog() == DialogResult.OK)
        {

            MessageBox.Show(fDialog.FileName.ToString());
        }

        string XMLdrzewo = fDialog.FileName.ToString();
        XDocument xdoc = XDocument.Load(XMLdrzewo);
        //// some code processing xml file
        /// not ready yet, have to write to that file the tree
        //structure of  selected XML file

        textBox2.Text = File.ReadAllText(XMLdrzewo);

ファイルが存在しない場合、FileNotFoundException was unhandled が発生します。

4

1 に答える 1

2

ファイル名を作成するコードは、if ステートメント内にある必要があります。

if (fDialog.ShowDialog == DialogResult.OK)
{

}

次に、最初に var などのファイルを作成する必要がありますstream = File.Create(filename)。次に、そのファイルに「作成するもの」を入力し、新しく作成したファイルにxml部分を保存できます。

何かのようなもの:

if (fDialog.ShowDialog() == DialogResult.OK)
{

    using (var newXmlFile = File.Create(fDialog.FileName);
    {
           var xd = new XmlDocument();
           var root = xd.AppendChild(xd.CreateElement("Root"));
           var child = root.AppendChild(xd.CreateElement("Child"));
           var childAtt = child.Attributes.Append(xd.CreateAttribute("Attribute"));
           childAtt.InnerText = "My innertext";
           child.InnerText = "Node Innertext";
           xd.Save(newXmlFile);
    }
}
于 2013-01-19T10:00:12.520 に答える