Reputation: 1247
An unhandled exception of type 'System.InvalidCastException' occurred in sCreator.exe Additional information: Unable to cast object of type 'System.String' to type 'sCreator.Shape'.
Here's the code:
public void Deseriaize(StreamReader file)
{
XmlSerializer ser = new XmlSerializer(typeof(string));
Shape s = (Shape)ser.Deserialize(file);
file.Close();
MessageBox.Show(s.title);
}
private void btn_OpenProject_Click(object sender, EventArgs e)
{
StreamReader file = new StreamReader(@"C:\Users\pb8n0053\Documents\SerializationOverview.seal");
Deseriaize(file);
}
Shape Class
[Serializable]
public class Shape
{
//Properties
public Draw draw;
public String title;
public float width { get; set; }
public float height { get; set; }
public float x { get; set; }
public float y { get; set; }
public static PointF center = new PointF(250f, 250f);
public int strokeThickness { get; set; }
public Color color { get; set; }
public float userDefinedWidth { get; set; }
public float userDefinedHeight { get; set; }
public int userDefinedStroke { get; set; }
public SizeF size;
public PointF location;
public float radius;
public ShapeType type;
public Status status;
public enum ShapeType
{
rectangle, square, circle, ellipse, triangle, image
}
public enum Status
{
editing, start
}
}
Upvotes: 0
Views: 2557
Reputation: 7039
Your XmlSerializer
is being created with typeof(string)
as the argument to the constructor. This means that that serializer is intended to convert XML to and from a System.String
. If you want it to convert your XML to and from your Shape
type, then initialize it using that instead:
public void Deseriaize(StreamReader file)
{
XmlSerializer ser = new XmlSerializer(typeof(Shape));
Shape s = (Shape)ser.Deserialize(file);
file.Close();
MessageBox.Show(s.title);
}
Note that your serialization/deserialization cycle will probably fail or work incorrectly if you try to deserialize XML that was not created with XmlSerializer
or if your Shape
class does not properly implement ISerializable
.
Upvotes: 3