Saving a variable data to disk

寵の児 提交于 2019-12-10 17:24:11

问题


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?


回答1:


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.




回答2:


You could use serialization, check this MSDN link, Serialization.

The default serialization options is binary and XML.




回答3:


Serialize it: http://msdn.microsoft.com/en-us/library/et91as27.aspx



来源:https://stackoverflow.com/questions/10229944/saving-a-variable-data-to-disk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!