写入用户定义的XML文件

时间:2015-04-25 00:28:10

标签: c# xml writing

我一直在关注创建列表并将其保存/加载到xml文件的Youtube教程。但是,我一直在玩它并且我似乎无法让我的头脑出现一个对话框,让用户选择一个位置并自己输入文件名。目前它是一个预定义的文件名和位置,每次保存时都会写入。这不是我想要的。

这是我的代码:

    private void button6_Click(object sender, EventArgs e)
    {
        string path = Directory.GetCurrentDirectory();

        if (!Directory.Exists(path + "\\TaskList")) // if the file directory doesnt exist..
            Directory.CreateDirectory(path + "\\TaskList"); // create the file directory

        if (!File.Exists(path + "\\TaskList\\settings.xml")) // if the XML file doesnt exist..
        {
            XmlTextWriter xW = new XmlTextWriter(path + "\\TaskList\\settings.xml", Encoding.UTF8); // create the xml file
            xW.WriteStartElement("TaskList");
            xW.WriteEndElement();
            xW.Close();
        }

        // create XML document to write to
        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(path + "\\TaskList\\settings.xml");

        // create node for every property inside the taskProperties class
        foreach (taskProperties newTask in task)
        {
            XmlNode nodeTop = xDoc.CreateElement("Task");
            XmlNode nodeTitle = xDoc.CreateElement("Title");
            XmlNode nodeDescription = xDoc.CreateElement("Description");
            XmlNode nodePriority = xDoc.CreateElement("Priority");
            XmlNode nodeCompletionDate = xDoc.CreateElement("CompletionDate");
            XmlNode nodeTaskComplete = xDoc.CreateElement("TaskComplete");

            nodeTitle.InnerText = newTask.title;
            nodeDescription.InnerText = newTask.description;
            nodePriority.InnerText = newTask.priority;
            nodeCompletionDate.InnerText = newTask.completionDate.ToFileTime().ToString(); // convert to file time (numbers) then to a string
            nodeTaskComplete.InnerText = newTask.taskComplete;

            // add these nodes to the 'nodeTop' node
            nodeTop.AppendChild(nodeTitle);
            nodeTop.AppendChild(nodeDescription);
            nodeTop.AppendChild(nodePriority);
            nodeTop.AppendChild(nodeCompletionDate);
            nodeTop.AppendChild(nodeTaskComplete);
            // add the nodeTop to the document
            xDoc.DocumentElement.AppendChild(nodeTop);
        }
        // save the document
        xDoc.Save(path + "\\TaskList\\settings.xml");
    }

任何有关如何实现这一目标的帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

使用此选项打开“文件保存”对话框并获取用户选择的位置。

SaveFileDialog fdgSave= new SaveFileDialog(); 
fdgSave.InitialDirectory = Convert.ToString(Directory.GetCurrentDirectory()); 
fdgSave.Filter = "XML (*.XML)|*.xml|All Files (*.*)|*.*" ; 
fdgSave.FilterIndex = 1; 

if(fdgSave.ShowDialog() == DialogResult.OK) 
{ 
    Console.WriteLine(fdgSave.FileName);//Do what you want here
} 
相关问题