问题
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