Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a variable data to disk

Tags:

c#

.net

xna

Is it possible to save a variable from C# to disk so that you are able to use it later in another instance of your project?

For example, I have a struct with 3 fields like in the following example :

struct MyStruct
{
    byte[] ByteData;
    int MyInt;
    double MyDouble;
};

I have an instance of this struct, let's say MyStruct S and I assign value to all my fields. After this step, I would like to save this variable somehow in disk so that I could use those stored values later in my program.

I know, that I could copy those value on a .txt file, but I would like to save the variable as it is on my disk so that I could directly load it into memory during the next runtime of my project.

Is it possible to save it somehow on the disk so that I could load it inside my program as it is?

like image 754
Simon Avatar asked Dec 27 '22 02:12

Simon


1 Answers

public void SerializeObject<T>(string filename, T obj)
   {
      Stream stream = File.Open(filename, FileMode.Create);
      BinaryFormatter binaryFormatter = new BinaryFormatter();
      binaryFormatter.Serialize(stream, obj);
      stream.Close();
   }

   public T DeSerializeObject<T> (string filename)
   {
      T objectToBeDeSerialized;
      Stream stream = File.Open(filename, FileMode.Open);
      BinaryFormatter binaryFormatter = new BinaryFormatter();
      objectToBeDeSerialized= (T)binaryFormatter.Deserialize(stream);
      stream.Close();
      return objectToBeDeSerialized;
   }

[Serializable]
struct MyStruct
{
    byte[] ByteData;
    int MyInt;
    double MyDouble;
}

Do not forget to mark your object as serializable.

like image 153
daryal Avatar answered Dec 30 '22 10:12

daryal