2012-11-15 2 views
0

WPF 응용 프로그램을 종료 할 때 개체 목록을 저장하는 WPF 응용 프로그램을 만들고 있습니다. 그리고 시스템 시작시 객체 목록을 얻습니다. 처음에는 모든 것이 잘 작동합니다. 하지만 어떤 때는 직렬화 예외를 제공합니다. 예외를 얻은 후에 XML 직렬화 된 파일을 보았습니다. 하지만 그것은 XML 파일이 제대로 형성되지 않았기 때문에 예외가 던져진 것처럼 보입니다. 내가 고칠 때. 다시 정상적으로 작동했습니다.개체 목록 Serialization xml 오류

public static class IsolatedStorageCacheManager<T> 
{ 
    public static void store(T loc) 
    { 
     IsolatedStorageFile appStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, null, null); 
     using(IsolatedStorageFileStream fileStream=appStore.OpenFile("myFile21.xml",FileMode.OpenOrCreate)) 
     { 
      DataContractSerializer serializer = new DataContractSerializer(typeof(T)); 
      serializer.WriteObject(fileStream, loc); 
     } 
    } 
    public static T retrieve() 
    { 
     T obj = default(T); 
     IsolatedStorageFile appStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, null, null); 
     if (appStore.FileExists("myFile21.xml")) 
     { 
      using (IsolatedStorageFileStream fileStream = appStore.OpenFile("myFile21.xml", FileMode.Open)) 
      { 
       DataContractSerializer serializer = new DataContractSerializer(typeof(T)); 
       try 
       { 
        obj = (T)serializer.ReadObject(fileStream); 
       } 
       catch (SerializationException e) 
       { 
        Console.WriteLine(e.StackTrace); 
       } 
      } 
     } 
     return obj; 
    } 
} 
+1

전달할 개체 중 하나 이상이 직렬화 가능하지 않을 수 있습니까? – CodingGorilla

+0

XML 파일이 제대로 형성되지 않았다는 것은 무엇을 의미합니까? 제대로 작동하려면 어떻게 수정해야합니까? –

답변

0

해야 할 첫 번째 일은 store에 전달 된 객체 유형 supported by the DataContractSerializer의 있는지 확인합니다.

가장 쉬운 방법은 모두 store에 전화를 걸어 확인하는 것입니다.

유효성 검사 방법을 만들거나 더 나은 방법으로 다른 사람이 구현 한 방법을 확인할 수도 있습니다. 이 메서드는 loc 개체를 확인하고 boolean을 반환하고 System.Diagnostics.Debug.Assert 호출 내에서 store 메서드의 시작 부분에서 호출하여 디버그 구성에서만 실행되도록 할 수 있습니다. 이 방법은 매우 까다로울 수 있습니다. 왜냐하면 DataContractSerializer의 스펙에 언급 된 모든 경우에 대해 유형 T를 검증해야하고 T가 일반 유효성 검증 T 매개 변수이기도하기 때문입니다.