2

我是编程新手。我正在使用 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"));
}
4

1 回答 1

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();
    }

如果您想花哨并遵循 Microsoft 的标准,那么将路径更改为您可以构建的内容 - Copy.xml 然后是内容 - Copy (1).xml 等。

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

编辑

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

于 2012-09-28T06:50:15.473 回答