Search code examples
c#serializationsystem.drawing

How to serialize Pen in C#?


I have a Shape class wich contains

public Pen outlinePen;  

What I try to do is to serialize List of Shape, but all I have isType

'System.Drawing.Pen' in Assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable.

If i mark this field as [field: NonSerialized()] then I can't use my loaded objects, because outlinePen is null.

Are there any other ways to serialize System.Drawing.Pen?


Solution

  • You should serialize only the data you interested in . Pen is a graphic object , so even if it would be possible, imo, it's not a good idea to store it.

    For example in your case you can store PenColor, PenWidth and PenStyle like a PenDataObject, which is kind of Pen lighweght object specially created to store Pen data.

    Hope this helps.