【问题标题】:Datacontractserializer doesn't overwrite all dataDatacontractserializer 不会覆盖所有数据
【发布时间】:2011-01-07 01:07:53
【问题描述】:

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

【问题讨论】:

    标签: c# serialization datacontractserializer


    【解决方案1】:

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

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

    尝试使用:

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

    请参阅FileMode 文档。

    【讨论】:

    • 干杯!这似乎已经解决了它。这两天我一直被这个困扰。 FileMode 选项我看的不够仔细。
    【解决方案2】:

    我相信这是由于使用了FileMode.OpenOrCreate。如果文件已经存在,我认为文件正在被打开并且部分数据正在从起始字节被覆盖。如果您改为使用FileMode.Create,它会强制覆盖所有现有文件。

    【讨论】:

    • 恐怕 Reddog 刚刚打败了你。无论如何,我已将您的答案标记为有用。干杯!
    猜你喜欢
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 2017-08-12
    • 2017-01-28
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多