Here is the code for serialization:
/// <summary>
/// Function to save object to external file
/// </summary>
/// <param name="_Object">object to save</param>
/// <param name="_FileName">File name to save object</param>
/// <returns>Return true if object save successfully, if not return false</returns>
public bool ObjectToFile(object _Object, string _FileName)
{
try
{
// create new memory stream
System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream();
// create new BinaryFormatter
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
= new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
// Serializes an object, or graph of connected objects, to the given stream.
_BinaryFormatter.Serialize(_MemoryStream, _Object);
// convert stream to byte array
byte[] _ByteArray = _MemoryStream.ToArray();
// Open file for writing
System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
// Writes a block of bytes to this stream using data from a byte array.
_FileStream.Write(_ByteArray, 0, _ByteArray.Length);
// close file stream
_FileStream.Close();
// cleanup
_MemoryStream.Close();
_MemoryStream.Dispose();
_MemoryStream = null;
_ByteArray = null;
return true;
}
catch (Exception _Exception)
{
// Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
// Error occured, return null
return false;
}
Here is the code for deserialize the object:
public object FileToObj(string _fileName)
{
FileStream fs = new FileStream(_fileName, FileMode.Open);
// create new BinaryFormatter
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
= new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
// Serializes an object, or graph of connected objects, to the given stream.
return _BinaryFormatter.Deserialize(fs);
}
A blog about web application development mainly on backend side
Subscribe to:
Post Comments (Atom)
What is DaemonSet in Kubernetes
A DaemonSet is a type of controller object that ensures that a specific pod runs on each node in the cluster. DaemonSets are useful for dep...
-
Cross-platform compatibility: MAUI allows developers to write code that can run on multiple platforms with minimal modifications. Shared cod...
-
Both .NET and NodeJS are popular programming frameworks that have their own strengths and weaknesses, which makes for an interesting compar...
-
A DaemonSet is a type of controller object that ensures that a specific pod runs on each node in the cluster. DaemonSets are useful for dep...
No comments:
Post a Comment