2011-01-07 83 views
1

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

回答

5

這是因爲你是如何與你的開料流的

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

嘗試使用:

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

FileMode文檔。

+0

乾杯!這似乎修復了它。在過去的幾天裏,我一直受這個困擾。我沒有像FileMode選項那樣仔細觀察。 – 2011-01-07 01:19:37

2

我相信這是由於使用FileMode.OpenOrCreate。如果文件已經存在,我認爲文件正在被打開,部分數據被從開始字節覆蓋。如果您更改爲使用FileMode.Create,則會強制覆蓋現有文件。

+0

恐怕Reddog只是打敗你。無論如何,我已經標記了你的答案。乾杯! – 2011-01-07 01:18:05