Reputation: 99
I am trying to serialize an object into a binary file. I am using BinaryFormatter.Serialize to serialize the object, but when I try to call it, I get a parser error on the stream argument, "Unexpected symbol `(' in class, struct, or interface member declaration".
This is my code:
using UnityEngine;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class Serializer{
Properties prop = new Properties ();
IFormatter f = new BinaryFormatter();
Stream s = new FileStream("Properties/prop.bin", FileMode.Create, FileAccess.Write, FileShare.None);
f.Serialize(s, prop);
s.Close();
}
The error is on:
f.Serialize(s, prop); //the error is on the 's'
and I am getting the same error here:
s.Close();
How can I fix these errors?
Here is what I am serializing:
public class Properties{
public string y = "2";
public string x = "4";
}
Upvotes: 0
Views: 1870
Reputation: 127563
Your code needs to be inside a function.
public class Serializer{
public void Seralize()
{
Properties prop = new Properties ();
IFormatter f = new BinaryFormatter();
Stream s = new FileStream("Properties/prop.bin", FileMode.Create, FileAccess.Write, FileShare.None);
f.Serialize(s, prop);
s.Close();
}
}
However I would recommend you avoid BinaryFormatter
assembly version changes can easily break your file, use XML or some other binary formatter instead.
Upvotes: 1