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 に答える