我正在尝试将用户创建的多个对象保存到二进制文件中。到目前为止,我能够创建一个对象的二进制文件。
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);
}
}
我不确定如何制作它以便将多个对象保存到二进制文件中。你有什么提示吗?
我确实尝试了以下内容:
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.
}
但问题是我不知道在哪里插入fileName
(路径)
答案 0 :(得分:1)
您可以修改BinaryFileSerialize
以接受数组:
public void BinaryFileSerialize(object [] objs, string filePath)
。然后,您可以遍历该数组以插入数组中的每个项目:
FileStream fileStream = new FileStream(filePath, FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
foreach(var obj in objs) {
b.Serialize(fileStream, obj);
}
SaveToFile
功能:
private void SaveToFile(string filename)
{
//Animal array
Animal [] animals = new Animal[animalmgr.Count];
for (int index = 0; index < animalmgr.Count; index++)
{
animals[index] = animalmgr.GetAt(index);
}
BinSerializerUtility BinSerial = new BinSerializerUtility();
BinSerial.BinaryFileSerialize(animals, filename);
}