Jason 0

Jason 0

  • NA
  • 1
  • 0

InvalidCastException thrown in Service code but not Form code

Nov 17 2005 11:38 AM
This is truly a wierd phenomenon. So I have this service that is going to backup files in realtime that get dumped into folders specified by the user. The user specifies various information for this service to use through a Windows.Forms GUI. That GUI uses a BinaryFormatter to both serialize the data into a file when the user exists the GUI, and deserialize that data when the GUI is opened again to load the data into the GUI. This works fine...no errors and it functions as expected. So I need my service to deserialize the same information from the file so it can do its thing given the settings the user set up right? Well I use practically the same approach that I used for the GUI, but in the service for some reason there is an explicit cast that causes a InvalidCastException to be thrown at runtime...This SAME cast does not throw an exception in the Forms GUI. Any ideas? Here is two snippets of code from the GUI and the Service. The explicit cast that causes the problem in the Service but not the GUI is the cast from the object "item" to an object of type OffSiteBackupServiceNamespace.Location. Note: fs is a filestream linked to the data file generated by the GUI GUI code (no compile time or run time errors): Object item = formatter.Deserialize(fs); ... if(item.GetType().ToString().Equals("OffSiteBackupServiceNamespace.Location")) { locations.Add((OffSiteBackupServiceNamespace.Location)item); addLocationSaveToView(); } Service code (no compile time errors, throws runtime InvalidCastException): Object item = formatter.Deserialize(fs); ... if(item.GetType().ToString().Equals("OffSiteBackupServiceNamespace.Location")) { //check if location is an active location? //then use it as a connection for the previous watchers //the code below throws the InvalidCastException if(((OffSiteBackupServiceNamespace.Location)item).Checked) { saveToLocations.Add((OffSiteBackupServiceNamespace.Location)item); this.myEventLog.WriteEntry("Active Location read: " + ((OffSiteBackupServiceNamespace.Location)item).ToString()); } } thx, jason