An InvalidCastException

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

hi ,

The Code like this:

public static Mapping Deserialize(string strXmlFilePath)
{
XmlSerializer s = new XmlSerializer(typeof(Mapping));
using (StreamReader sr = new StreamReader(strXmlFilePath))
{
object o = s.Deserialize(sr);
Mapping m = (Mapping)o;
return m;
}
}

Sometimes ,it will throw an InvalidCastException.
The strXmlFilePath refer to a same file ,but sometimes it works well
,sometimes it throws a exception.
I can't catch this exception in a debuger,because it always works well in
the debuger.
Anyone know what's wrong?

thanks
 
if the Deserialize function fails it will return null and when you try
to cast that to Mapping you'll get an invalid cast exception. It's
probably working in Debug mode because your using a relative path.

Jan
 
Jan said:
if the Deserialize function fails it will return null and when you try
to cast that to Mapping you'll get an invalid cast exception. It's
probably working in Debug mode because your using a relative path.

No, casting null works fine:

using System;

class Test
{
static void Main()
{
object o = null;
string s = (string)o;

Console.WriteLine ("s is null? {0}", s==null);
}
}
 
Ah yes, my mistake.

It must be the Deserialize function failing to parse you xml stream
into your mapping.
 
Was the object serialized in the same program or from a different
program? If from a different program, did you copy the Mapping class
file to the other program and compile or did you put it in a
ClassLibrary and compile it that way?

You need to put your mapping class in a ClassLibrary if you intend to
serialize/deserialize across applications.
 
I'm using the Mapping class in two program , one is an add-in for VS IDE, the
other is a form application.The exception just sometimes occurs in the
add-in. Yes, the Mapping class is put in an individual class library, the two
program reference to the same dll. And I can promise these two program all
open the same and valid file.

And I don't think in XML serialization assembly version is a problem ,
assembly version just may cause problem in binary serialization. In XML
serialization, where the class resides in or even whether the class is
complete identity is not important.
 
Back
Top