我注意到,如果我使用Datacontractserializer將對象保留迴文件中,如果新xml的長度比最初存在於文件中的xml更短,則原始xml的殘留與新的XML的長度將保留在文件中,並將打破XML。Datacontractserializer不覆蓋所有數據
有沒有人有一個很好的解決方案來解決這個問題?
下面是我使用的持久化對象的代碼:
/// <summary>
/// Flushes the current instance of the given type to the datastore.
/// </summary>
private void Flush()
{
try
{
string directory = Path.GetDirectoryName(this.fileName);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
FileStream stream = null;
try
{
stream = new FileStream(this.fileName, FileMode.OpenOrCreate);
for (int i = 0; i < 3; i++)
{
try
{
using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, new System.Text.UTF8Encoding(false)))
{
stream = null;
// The serializer is initialized upstream.
this.serializer.WriteObject(writer, this.objectValue);
}
break;
}
catch (IOException)
{
Thread.Sleep(200);
}
}
}
finally
{
if (stream != null)
{
stream.Dispose();
}
}
}
catch
{
// TODO: Localize this
throw;
//throw new IOException(String.Format(CultureInfo.CurrentCulture, "Unable to save persistable object to file {0}", this.fileName));
}
}
乾杯!這似乎修復了它。在過去的幾天裏,我一直受這個困擾。我沒有像FileMode選項那樣仔細觀察。 – 2011-01-07 01:19:37