I do not know if this is even possible but let's suppose I have a class:
[Serializable]
public class Test
{
//Properties and functions would go here.
public void SaveClass(string FilePath)
{
System.IO.Stream stream = System.IO.File.Create(FilePath);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, this);
stream.Close();
}
public void LoadClass(string FilePath)
{
System.IO.Stream stream = System.IO.File.OpenRead(FilePath);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
this = binaryFormatter.Deserialize(stream); //It returns an error saying that 'this' is readonly.
stream.Close();
}
}
Now I want to be able to Save and Load the class. The SaveClass
is working fine, but the LoadClass
returns an error, because I can not assign anything to this
. Is there a way that I could load the class from a file, or is this impossible.
CodePudding user response:
Make LoadClass
static, something like:
public static Test LoadClass(string FilePath)
{
System.IO.Stream stream = System.IO.File.OpenRead(FilePath);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
var newTest = (Test)binaryFormatter.Deserialize(stream);
stream.Close();
return newTest;
}