2010-04-07 26 views
1

我正在使用单例类来保存我所有的设置信息。它首先被调用Settings.ValidateSettings(@"C:\MyApp").NET XmlSerializer失败,列表<T>

我遇到的问题是“列表联系人”导致xmlserializer无法写入设置文件或加载所述设置。如果我注释掉List<T>,那么我在保存/加载xml文件时没有问题。我究竟做错了什么?

// The actual settings to save 

public class MyAppSettings 
{ 
    public bool FirstLoad 
    { get; set; } 

    public string VehicleFolderName 
    { get; set; } 

    public string ContactFolderName 
    { get; set; } 

    public List<ContactInfo> Contacts 
    { 
     get 
     { 
      if (contacts == null) 
       contacts = new List<ContactInfo>(); 
      return contacts; 
     } 
     set 
     { 
      contacts = value; 
     } 
    } 

    private List<ContactInfo> contacts; 
} 

// The class in which the settings are manipulated 
public static class Settings 
{ 
    public static string SettingPath; 
    private static MyAppSettings instance; 
    public static MyAppSettings Instance 
    { 
     get 
     { 
      if (instance == null) 
       instance = new MyAppSettings(); 
      return instance; 
     } 
     set 
     { 
      instance = value; 
     } 
    } 

    public static void InitializeSettings(string path) 
    { 
     SettingPath = Path.GetFullPath(path + "\\MyApp.xml"); 
     if (File.Exists(SettingPath)) 
     { 
      LoadSettings(); 
     } 
     else 
     { 
      Instance.FirstLoad = true; 
      Instance.VehicleFolderName = "Cars"; 
      Instance.ContactFolderName = "Contacts"; 
      SaveSettingsFile(); 
     } 
    } 

    // load the settings from the xml file 
    private static void LoadSettings() 
    { 
     XmlSerializer ser = new XmlSerializer(typeof(MyAppSettings)); 

     TextReader reader = new StreamReader(SettingPath); 
     Instance = (MyAppSettings)ser.Deserialize(reader); 
     reader.Close(); 
    } 

    // Save the settings to the xml file 
    public static void SaveSettingsFile() 
    { 
     XmlSerializer ser = new XmlSerializer(typeof(MyAppSettings)); 

     TextWriter writer = new StreamWriter(SettingPath); 
     ser.Serialize(writer, Settings.Instance); 
     writer.Close(); 

    } 

    public static bool ValidateSettings(string initialFolder) 
    { 
     try 
     { 
      Settings.InitializeSettings(initialFolder); 
     } 
     catch (Exception e) 
     { 
      return false; 
     } 

     // Do some validation logic here 

     return true; 
    } 
} 

// A utility class to contain each contact detail 
public class ContactInfo 
{ 
    public string ContactID; 
    public string Name; 
    public string PhoneNumber; 
    public string Details; 
    public bool Active; 
    public int SortOrder; 

} 
+3

似乎对我的工作 - 你看到了什么错误? – itowlson 2010-04-07 01:22:22

回答

0

@itowlson 您的回复后,我加载代码文件到一个新的窗体应用程序和它的工作。我正在处理的项目实际上是另一个程序的插件。所以这是因为事情是在我的掌握所造成的串行失败,并列出

感谢回答,它为你工作,这让我意识到发生了什么