I'm trying to save multiple object that the user create to a binary file. So far I am able to create a binary file of one object.
public class BinSerializerUtility
{
public void BinaryFileSerialize(object obj, string filePath)
{
FileStream fileStream = null;
try
{
fileStream = new FileStream(filePath, FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
b.Serialize(fileStream, obj);
}
catch
{
throw;
}
finally
{
if (fileStream != null)
fileStream.Close();
}
}
MainForm:
private void SaveToFile(string filename)
{
for (int index = 0; index < animalmgr.Count; index++)
{
Animal animal = animalmgr.GetAt(index);
BinSerializerUtility BinSerial = new BinSerializerUtility();
BinSerial.BinaryFileSerialize(animal, filename);
}
}
private void mnuFileSaveAs_Click(object sender, EventArgs e)
{
//Show save-dialogbox
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string thefilename = saveFileDialog1.FileName;
SaveToFile(thefilename);
}
}
I'm not really sure how to make it so it can save multiple objects to binary file. Do you have any tips?
I did try the following:
public byte[] SerializeArray(object obj)
{
byte[] serializedObject = null;
MemoryStream memStream = null;
try
{
memStream = new MemoryStream();
BinaryFormatter binFormatter = new BinaryFormatter();
binFormatter.Serialize(memStream, obj);
memStream.Seek(0, 0); //set position at 0,0
serializedObject = memStream.ToArray();
}
finally
{
if (memStream != null)
memStream.Close();
}
return serializedObject; // return the array.
}
But the problem with it is that I don't know where to insert the fileName (The path)