我注意到,如果我使用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