如何在文件中存储自定义结构的数组?

时间:2012-10-21 05:18:01

标签: c#

我有一个简单的结构,如下所示。

public struct Structure
{
    public byte Style;
    public string Value1;
    public string Value2;
    public int Value3;
    public bool Active;
}

我想使用可变大小作为文件存储此结构的数组。该文件将在程序启动时自动加载,并在程序使用时更新。我可以弄清楚如何在程序中使用它,我只是不确定我应该用来存储它的方法。我猜我应该为每个值使用带前缀字节长度的二进制写入器?如果这是正确的,那么如何存储和加载Structure [X]数组的示例将非常有用。出于审美原因,我想将其保存在带有自定义扩展名的文件中(即:Array.ext),但我并不反对任何其他解决方案,以便在启动之间保持以该格式存储的数据。

2 个答案:

答案 0 :(得分:2)

您可以向此添加[Serializable]并使用二进制序列化将数据序列化为字节数组。你可以把它保存到文件中。

public static string Serialize(object o)
{
    using (var s = new FileStream())
    {
        _binaryFormatter.Serialize(s, o);
    }
}

答案 1 :(得分:1)

您有几个选择。如果您需要以可读格式存储文件,则可以使用XML或JSON Serializer / Deserializer。这是一个XML示例

public static void Serialize(Structure[] input) 
{
  var serializer = new XmlSerializer(input.GetType());
  var sw= new StreamWriter(@"C:\array.ext");
  serializer.Serialize(sw, input);
  sw.Close();
}    

public static Structure[] Deserialize() 
{
  var stream = new StreamReader(@"C:\array.ext");
  var ser = new XmlSerializer(typeof(Structure[]));
  object obj = ser.Deserialize(stream);
  stream.Close();
  return (Structure[])obj;
}

如果要使用二进制序列化器

public static void Serialize(Structure[] input) 
{
    var stream = new StreamWriter(@"C:\Array.ext");
    var bformatter = new BinaryFormatter();    
    bformatter.Serialize(stream, input);
    stream.Close();
}

public static Structure[] Deserialize() 
{
    var stream = new StreamReader(@"C:\array.ext");
    var bformatter = new BinaryFormatter();
    var obj = bformatter.Deserialize(stream);
    stream.Close();
    return (Structure[])object;
}

您还需要将您的课程标记为[Serializable]

[Serializable]
public class Structure { //etc