开发者

Datacontractserializer doesn't overwrite all data

开发者 https://www.devze.com 2023-02-03 12:08 出处:网络
I\'ve noticed that if I persist an object back into file using a Datacontr开发者_开发问答actserializer, if the length of the new xml is shorter than the xml originally present in the file the remnants

I've noticed that if I persist an object back into file using a Datacontr开发者_开发问答actserializer, if the length of the new xml is shorter than the xml originally present in the file the remnants of the original xml outwith the length of the new xml will remain in the file and will break the xml.

Does anyone have a good solution to fix this?

Here's the code I am using to persist the object:

    /// <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));
        }
    }


It's because of how you are opening your stream with:

stream = new FileStream(this.fileName, FileMode.OpenOrCreate);

Try using:

stream = new FileStream(this.fileName, FileMode.Create);

See FileMode documentation.


I believe this is due to using FileMode.OpenOrCreate. If the file already exits, I think the file is being opened and parts of the data are being overwritten from the start byte. If you change to using FileMode.Create it forces any existing files to be overwritten.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号