您有幾個選項。如果您需要將文件以可讀格式存儲,則可以使用XML或JSON串行器/解串器。下面是一個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
爲什麼不使用一些基於文件的數據庫,如SQLite,例如? –