2011-01-07 17 views
1

私は、Dataacontractserializerを使用してオブジェクトをファイルに戻しておくと、新しいxmlの長さがファイルに元々存在していたxmlよりも短い場合、元のxml outwith新しいxmlの長さは、ファイルに残り、xmlを壊すことになります。Datacontractserializerはすべてのデータを上書きしません

これを解決するには誰も良い解決策を持っていますか?私は、これはFileMode.OpenOrCreateを使用してによるものであると考えてい

/// <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のオプションとして十分に見ていませんでした。 –

2

は、ここで私は、オブジェクトを永続化するために使用していたコードです。ファイルがすでに終了している場合は、ファイルが開かれていると思われ、データの一部が開始バイトから上書きされていると考えられます。 FileMode.Createを使用するように変更すると、既存のファイルを強制的に上書きします。

+0

私は恐れているReddogはあなたにそれを打ち負かす。私はあなたの答えをとにかく役に立つとマークしました。乾杯! –

関連する問題