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

Rav*_*her 2 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"));
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*han 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();
    }
Run Code Online (Sandbox Code Playgroud)

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

tempPath = path + "(" + counter + ")" + ".xml";
Run Code Online (Sandbox Code Playgroud)

编辑

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