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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With