I have an ArrayList which consist of lots of object created by me. I am trying to keep it. As far as I look, the best solution for that is to use binary formatter. But something is wrong with my code. It doesn't work either writing or reading. Here is my code;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private ArrayList allList = new ArrayList();
private FileStream fileStream;
private MemoryStream memoryStream;
public Form1()
{
InitializeComponent();
fileStream = new FileStream("pcdata.dat",FileMode.OpenOrCreate,FileAccess.ReadWrite);
memoryStream = new MemoryStream();
}
public void acceptDevice(Device receivedDevice)
{
//Somehow I call this method
allList.Add(receivedDevice);
saveDeviceDataToFileStream();
}
private void saveDeviceDataToFileStream()
{
SerializeToStream(allList).WriteTo(fileStream);
}
private void loadDeviceDataFromFileStream()
{
fileStream.CopyTo(memoryStream);
allList = (ArrayList)DeserializeFromStream(memoryStream);
}
public static MemoryStream SerializeToStream(object o)
{
MemoryStream stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, o);
return stream;
}
public static object DeserializeFromStream(MemoryStream stream)
{
IFormatter formatter = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
if (null == stream)
{
return null;
}
object o = formatter.Deserialize(stream);
return o;
}
}
}
This is my device class:
namespace WindowsFormsApplication1
{
[Serializable]
public class Device
{
public MyPanel panel; //panel class that I created
public String id;
public int deviceNumber;
public Device(String id, int deviceNumber)
{
panel = new MyPanel();
this.id = id;
this.deviceNumber = deviceNumber;
}
}
}
And this is myPanel class:
namespace WindowsFormsApplication1
{
public class MyPanel : TableLayoutPanel
{
public Panel panel1 = new Panel();
public Panel panel2 = new Panel();
public Panel panel3 = new Panel();
public Panel panel4 = new Panel();
public PictureBox pictureBox1 = new PictureBox();
public Label nameLabel = new Label();
public MyPanel()
{
//...
}
}
}
This is it. When I tried to tun it I get this exception :
SerializationException was unhandled
An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll
Additional information: 'WindowsFormsApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' Derlemesindeki 'WindowsFormsApplication1.MyPanel' ...
I dont think you will be able to just serialize controls like that. I would suggest creating classes around the data you want to save and make the controls only responsible for display.
[Serializable]
public class MyPanelInfo
{
public PanelInfo panel1;
public PanelInfo panel2;
public PanelInfo panel3;
public PanelInfo panel4;
public Image image;
public string nameLabel;
public MyPanelInfo()
{
}
}
[Serializable]
public class PanelInfo
{
public string id;
public string name;
}