C# 根据其他XML文件的存在创建不同的XML文件#
在保存数据时出现问题,我试图设置它,以便如果用户尝试保存其角色的名称数据,并且文件已经存在,它将创建第二个xml文件“NameData2.xml”,以此类推,直到最多达到3个文件(因此用户可以选择不同的字符)然而,目前它只是一次创建两个xml文件,所有文件都包含相同的名称(我猜这是因为他们在同一个if-else语句中同时检查所有内容?当我试图找到答案时,我所能找到的只是如何检查文件的存在,如果它找不到如何创建文件,我将在下面发布我的代码,如果有人有任何建议,这将是非常精彩的,因为我非常难堪 先谢谢你C# 根据其他XML文件的存在创建不同的XML文件#,c#,xml,saving-data,C#,Xml,Saving Data,在保存数据时出现问题,我试图设置它,以便如果用户尝试保存其角色的名称数据,并且文件已经存在,它将创建第二个xml文件“NameData2.xml”,以此类推,直到最多达到3个文件(因此用户可以选择不同的字符)然而,目前它只是一次创建两个xml文件,所有文件都包含相同的名称(我猜这是因为他们在同一个if-else语句中同时检查所有内容?当我试图找到答案时,我所能找到的只是如何检查文件的存在,如果它找不到如何创建文件,我将在下面发布我的代码,如果有人有任何建议,这将是非常精彩的,因为我非常难堪 先谢
// This will save the users generated name in a created file
// NameData.xml and will take the user to the partySelectionScreen.
private void continueButton_Click(object sender, RoutedEventArgs e)
{
try
{
NameSavingInformation nameInfo = new NameSavingInformation();
nameInfo.GeneratedName = generatedNameTexbox.Text;
SaveXml.SaveData(nameInfo, "NameData.xml");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if(File.Exists("NameData.xml"))
{
NameSavingInformation nameInfo = new NameSavingInformation();
nameInfo.GeneratedName = generatedNameTexbox.Text;
SaveXml.SaveData(nameInfo, "NameData2.xml");
}
else if (File.Exists("NameData2.xml"))
{
NameSavingInformation nameInfo = new NameSavingInformation();
nameInfo.GeneratedName = generatedNameTexbox.Text;
SaveXml.SaveData(nameInfo, "NameData3.xml");
}
else if (File.Exists("NameData3.xml"))
{
MessageBox.Show("You have passed the limit of existing characters" +
"To continue please return to the main menu and delete at least 1 character");
}
你应该这样做。
这将对不存在的文件执行搜索并生成它们。这将允许用户在不破坏算法的情况下删除所需的任何字符
private void continueButton_Click(object sender, RoutedEventArgs e)
{
if(!File.Exists("NameData.xml"))
{
SaveFileInfo("NameData.xml");
}
else if (!File.Exists("NameData2.xml"))
{
SaveFileInfo("NameData2.xml");
}
else if (!File.Exists("NameData3.xml"))
{
SaveFileInfo("NameData3.xml");
}
else
{
MessageBox.Show("You have passed the limit of existing characters" +
"To continue please return to the main menu and delete at least 1 character");
}
}
public SaveFileInfo(string fileName)
{
try
{
NameSavingInformation nameInfo = new NameSavingInformation();
nameInfo.GeneratedName = generatedNameTexbox.Text;
SaveXml.SaveData(nameInfo, fileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
太好了,非常感谢你花时间回答!