我有一个显示轨道车列表的DataGridView,并有几个用于操作列表的按钮(添加,编辑,删除,保存)。 DGV的内容来自XML文件,并在单击“保存”按钮时保存回同一文件。除“删除”按钮外,此表单的所有功能都可以正常工作。当我从列表中删除轨道车并单击“保存”时,将删除"删除"行并以非常奇怪的方式将其重新附加到XML文件(图片如下)。
以下是表单的代码(我只包括Save& Delete按钮和XML处理以便于阅读):
public partial class SimulatedTrainEditor : Form
{
//fileName and XML variables for serialization/deserialization
const string fileName = "SimulatedTrain1.xml";
XmlSerializer xml = new XmlSerializer(typeof(BindingList<SimulatedTrain>));
//Create BindingList object to hold XML data
public BindingList<SimulatedTrain> NewSimulatedTrain = new BindingList<SimulatedTrain>();
public bool WereChangesMade;
public SimulatedTrainEditor()
{
InitializeComponent();
LoadXML();
this.dataGridViewSimulatedTrainEditor.DataSource = NewSimulatedTrain;
this.dataGridViewSimulatedTrainEditor.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridViewSimulatedTrainEditor.AllowUserToAddRows = false;
this.WereChangesMade = false;
this.buttonSaveXML.Enabled = false;
}
public void LoadXML()
{
try
{
using (var fs = new FileStream(fileName, FileMode.Open))
{
NewSimulatedTrain = (BindingList<SimulatedTrain>)xml.Deserialize(fs);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message, ex);
}
}
private void buttonRemoveRailCar_Click(object sender, EventArgs e)
{
var currentRow = this.dataGridViewSimulatedTrainEditor.CurrentRow;
if (currentRow != null)
{
this.NewSimulatedTrain.RemoveAt(currentRow.Index);
this.WereChangesMade = true;
this.buttonSaveXML.Enabled = true;
}
}
private void buttonSaveXML_Click(object sender, EventArgs e)
{
//are there any changes?
if (WereChangesMade)
{
//save the file if changes
using (var fs = new FileStream(fileName, FileMode.OpenOrCreate))
{
xml.Serialize(fs, this.NewSimulatedTrain);
}
//Disable the SaveXML button when it's clicked to look for new edits after each save
this.buttonSaveXML.Enabled = false;
}
}
}
以下是我删除行之前和之后的截图(这只是XML的底部):
您可以看到它在输入应该删除的行数据后尝试将另一个关闭的ArrayOfSimulatedTrain标记添加到结尾。我仍然习惯使用XML文件,但在少数情况下,我以前做过这类工作,但我从未遇到过这个问题。
答案 0 :(得分:1)
在FileStream
模式下使用FileMode.OpenOrCreate
不会在写入之前擦除文件内容。
编辑XML会更改将在文件中写入的内容的长度。如果新XML较短,则文件末尾会有一些剩余部分。来自MSDN:
如果用较短的字符串(例如“Second run”)覆盖较长的字符串(例如“这是对OpenWrite方法的测试”),该文件将包含字符串的混合(“Second runtest of OpenWrite方法“)。
您需要将流的FileMode
更改为FileMode.Create
以覆盖整个文件:
//save the file if changes
using (var fs = new FileStream(fileName, FileMode.Create))
{
xml.Serialize(fs, this.NewSimulatedTrain);
}