Datacontractserializer不会覆盖所有数据

Jam*_*uth 1 c# serialization datacontractserializer

我注意到如果我使用Datacontractserializer将一个对象保存回文件,如果新xml的长度比文件中最初存在的xml短,那么原始xml的残余与新xml的长度将保持在一起该文件将打破xml.

有没有人有解决这个问题的好方法?

这是我用来持久保存对象的代码:

    /// <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));
        }
    }
Run Code Online (Sandbox Code Playgroud)

Red*_*dog 5

这是因为您打开流的方式:

stream = new FileStream(this.fileName, FileMode.OpenOrCreate);
Run Code Online (Sandbox Code Playgroud)

尝试使用:

stream = new FileStream(this.fileName, FileMode.Create);
Run Code Online (Sandbox Code Playgroud)

FileMode文档.