2

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.

Jonathan Barraone
  • 489
  • 1
  • 3
  • 20
  • 1
    as a matter of a better design - separate serialization logic from the data – Daniel A. White Nov 22 '22 at 18:36
  • `LoadClass` should be a static method returns a deserialized `Test` instance. `public static Test LoadClass(string FilePath) { //deserialize, cast and return }`. – dr.null Nov 22 '22 at 18:47

1 Answers1

2

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;
 }
SoloAle
  • 124
  • 3