如何在创建XML时为XML文件提供动态名称

时间:2012-09-28 06:43:43

标签: c# xml winforms

我是编程新手。我正在使用Windows窗体创建一个XML文件,我的XML文件的名称是Windows窗体的名称字段文本框文本,它的工作正常,但如果文件已经可用我想给新名称,但我能够给不同的名字只有一次。例如,如果'dog.xml'已经存在,那么我可以创建dog1.xml文件,然后每当我创建任何新文件时,'dog1.xml'文件的内容被替换为新文件内容,但我想创建' dog11.xml'或'dog2.xml'文件

private void btnSave_Click(object sender, EventArgs e)
{
    path = rtxtName.Text + ".xml";//name of a xml file is name of WPF 'name' field 
    doc = new XmlDocument(); //Here i am creating the xmldocument object
    doc.CreateTextNode(path);
    if (!System.IO.File.Exists(path))//if there is no file exists then
    {
        CreateNewXMLDoc();
    }
    else
    {
        path = rtxtName.Text + "1.xml"; //If the file is already avaliable          
        CreateNewXMLDoc();
    }
}

public void CreateNewXMLDoc() //This method is for creating my xml file
{
    XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
    XmlComment comment = doc.CreateComment("This is a generated XML file");
    doc.AppendChild(declaration);
    doc.AppendChild(comment);
    doc.AppendChild(doc.CreateElement("root"));
}

1 个答案:

答案 0 :(得分:5)

    private void btnSave_Click(object sender, EventArgs e)
    {
        path = rtxtName.Text;//name of a xml file is name of WPF 'name' field 

        doc = new XmlDocument(); //Here i am creating the xmldocument object

        string tempPath = path;
        int counter = Properties.Settings.Default.Counter;

        while(System.IO.File.Exists(tempPath))
        {
            counter++;
            tempPath = path + counter + ".xml";
        }

        Properties.Settings.Default.Counter = counter;
        Properties.Settings.Default.Save();
        doc.CreateTextNode(path);
        CreateNewXMLDoc();
    }

如果您想要看中并遵循微软标准,那么请改变它的路径 你可以构建一些东西 - Copy.xml然后是东西 - 复制(1).xml等等。

tempPath = path + "(" + counter + ")" + ".xml";

修改

更新以在应用程序重新启动时保留计数器