[英]read multiple struct from binary file in c#
我想在二进制文件中插入数据。数据为50 struct.i我想将柔和音乐文件的功能保存在二进制文件中,作为我可以使用的数据库。
我为每首歌曲构建了一个结构,并将其插入文件中。 结构包含:
public struct s {
public byte class_no;
public int sample_no;
public byte [] template;
}
其中模板是大小为4410的一维数组,我的文件现在包含50个结构,我想使用二进制文件读取它,并在文件中制作所有结构的结构数组
我将回答从文件读取多个结构的问题。
这个例子定义了一个保存数据的结构,您将需要使用它来做自己的事情。
这些都不是为满足您的特定需求而设计的,但是作为一般方法,如何保存和读取自定义结构的列表
完整的代码,您可以复制并粘贴到新的控制台应用程序项目中:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
//where the magic lives
using System.Runtime.Serialization.Formatters.Binary;
namespace savecon
{
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
byte[] data = new byte[20];
rand.NextBytes(data);
DataObj a = new DataObj(data);
DataObj b = new DataObj(data);
DataCollection dc_old = new DataCollection();
dc_old.Add(a);
dc_old.Add(b);
DataCollection.ToFile("D:\\data.my",dc_old);//I use D: drive yours will be different
DataCollection dc_new = DataCollection.FromFile("D:\\data.my");
}
}
[Serializable]//the magic
struct DataObj
{
byte[] data;
public DataObj(byte[] d)
{
data = d;
}
}
[Serializable]//more magic
class DataCollection : IEnumerable<DataObj>
{
List<DataObj> dataobjects;//list<> is Attributed with Serializable as well
public DataCollection()
{
dataobjects = new List<DataObj>();
}
public static DataCollection FromFile(string path)
{
DataCollection dcol;
using (FileStream FS = File.OpenRead(path))
{
dcol = (DataCollection)new BinaryFormatter().Deserialize(FS); // magic happening
}
return dcol;
}
public static void ToFile(string path,DataCollection DC)
{
using (FileStream FS = File.Open(path, FileMode.Create, FileAccess.ReadWrite))
{
new BinaryFormatter().Serialize(FS, DC);
}
}
public void Add(DataObj dobj)
{
dataobjects.Add(dobj);
}
//note that Ienumerable does not matter for serializing (saving the data)
public IEnumerator<DataObj> GetEnumerator()
{
return dataobjects.AsEnumerable().GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return dataobjects.GetEnumerator();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.