2011-01-07 4 views
1

나는 Datacontractserializer를 사용하여 객체를 파일에 다시 저장하면 새 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이 당신을 때리는 것에 두려워합니다. 어쨌든 당신의 대답을 유용하다고 표시했습니다. 건배! –

관련 문제