保存可变数据到磁盘 [英] Saving a variable data to disk
问题描述
时可以节约从C#到磁盘上的变量,以便您能够在您的项目的另一个实例中用到它?
例如,我有3个领域,如下面的示例结构:
结构MYSTRUCT
{
byte []的ByteData;
INT敏;
双MyDouble;
};
我有这样的结构的一个实例,让我们说 MYSTRUCT小号
,我将值分配给我的所有领域。
经过这一步,我想以某种方式保存该变量的磁盘,这样我可以在我的程序后使用这些存储的值。
我知道,我可以复制上一个txt文件的价值,但我想保存的变量,因为它是在我的硬盘,这样我可以我的项目的下一个运行期间直接加载到内存中。
是否有可能以某种方式保存在磁盘上,这样我可以我的程序中加载它,因为它是?
公共无效SerializeObject< T>(字符串文件名,T OBJ)
{
流流= File.open方法(文件名,FileMode.Create);
的BinaryFormatter的BinaryFormatter =新的BinaryFormatter();
binaryFormatter.Serialize(流OBJ);
stream.Close();
}
公共牛逼DeSerializeObject< T> (字符串文件名)
{
牛逼objectToBeDeSerialized;
流流= File.open方法(文件名,FileMode.Open);
的BinaryFormatter的BinaryFormatter =新的BinaryFormatter();
objectToBeDeSerialized =(T)binaryFormatter.Deserialize(流);
stream.Close();
返回objectToBeDeSerialized;
}
[可序列化]
结构MYSTRUCT
{
byte []的ByteData;
INT敏;
双MyDouble;
}
不要忘记标记您的对象序列化。
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.
这篇关于保存可变数据到磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!