2010-03-23 18 views
8
public void Save() { 
      XmlSerializer Serializer = new XmlSerializer(typeof(DatabaseInformation)); 
      /* 
      A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll 
      A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll 
      A first chance exception of type 'System.InvalidOperationException' occurred in System.Xml.dll 
      */ 

      // .... 
    } 

Ésta es toda la clase si lo necesita:¿Por qué XmlSerializer arroja una InvalidOperationException?

public class DatabaseInformation 
{ 
    /* Create new database */ 
    public DatabaseInformation(string name) { 
     mName = name; 
     NeedsSaving = true; 
     mFieldsInfo = new List<DatabaseField>(); 
    } 

    /* Read from file */ 
    public static DatabaseInformation DeserializeFromFile(string xml_file_path) 
    { 
    XmlSerializer Serializer = new XmlSerializer(typeof(DatabaseInformation)); 
     TextReader r = new StreamReader(xml_file_path); 
     DatabaseInformation ret = (DatabaseInformation)Serializer.Deserialize(r); 
     r.Close(); 
     ret.NeedsSaving = false; 
     return ret; 
    } 

    /* Save */ 
    public void Save() { 
    XmlSerializer Serializer = new XmlSerializer(typeof(DatabaseInformation)); 
     if (!mNeedsSaving) 
      return; 

     TextWriter w = new StreamWriter(Path.Combine(Program.MainView.CommonDirectory.Get(), Name + ".xml"), false); 
     Serializer.Serialize(w, this); 
     w.Close(); 
     NeedsSaving = false; 
    } 

    private string mName; 
    public string Name { get { return mName; } } 

    private bool mNeedsSaving; 
    public bool NeedsSaving { get { return mNeedsSaving; } set { mNeedsSaving = value; Program.MainView.UpdateTitle(value); } } 

    private bool mHasId; 
    public bool HasId { get { return mHasId; } } 

    List<DatabaseField> mFieldsInfo; 
} 

(PD: si tiene algún consejo para mejorar mi código sensación de compartir libre, soy un principiante C#)

+0

¿Podría pegar mensajes de excepción aquí? –

+1

Publique la información de excepción completa, incluidas las excepciones internas y los textos de documentación correspondientes (es decir, el mensaje). Realmente extrañas el mensaje que a menudo contiene más información. – TomTom

Respuesta

13

Para serializar/deserializar su tipo, necesita tener un constructor sin parámetros. Salida here:

Una clase debe tener un constructor por defecto que se serializa XmlSerializer.

+6

Mi tipo tiene constructor sin parámetros y todavía tengo este error. Resulta que la causa era una propiedad pública con tipo Uri que no tiene constructor sin parámetros. Entonces, además de su tipo, también sus propiedades públicas en ese tipo también deben tener un constructor sin parámetros. – user850010

+0

me salvó el día !!! – Leviathan

+0

Cuando detecté esta excepción y examiné varios niveles de InnerException asociados a ella, encontré que uno de mis objetos anidados tenía un miembro cuyo tipo es una interfaz (IEnumerable) y que no es serializable. Creo que tendré que convertir esto a un tipo concreto. – Neek

6

oh .. no sabía que tenía información adicional (tenía que hacer clic en "Ver detalle .."), misterio resuelto:

Mensaje = SDB.DatabaseInformation no puede ser serializado porque no tiene un constructor sin parámetros.

0

Puede evitar esto proporcionando un constructor predeterminado que llame al constructor sobrecargado. Por ejemplo:

public DatabaseInformation() : this ("defaultName"){} 
1

También conseguía esta excepción, pero no se debió a la falta de un constructor por defecto. Tenía algunas propiedades adicionales (List y Dictionary) que no forman parte del documento XML.

Decorar esas propiedades con [XmlIgnore] resolvió el problema para mí.

Cuestiones relacionadas