C# simple serialization and deserialization

        // Serialization                                                 
        public  void Serialize(Book book)
        {

            using (FileStream fs = new FileStream(strFile, FileMode.Create))         // FileMode.Create opens or creates a file                                                 
            {
                 // Serialize and deserialize the object or the entire connection object graph in binary format.                                                
                BinaryFormatter formatter = new BinaryFormatter();
                 // Serialize the Book object graph to the given stream.                                                 
                formatter.Serialize(fs, book);
            }
        }



        // Deserialize                                                 
        public Book DeSerialize()
        {
            Book book;
            using (FileStream fs = new FileStream(strFile, FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                 // Deserialize the specified stream into a book object                                                 
                book = (Book)formatter.Deserialize(fs);                             // Executing this method to return an Object object needs to be cast                     
            }
             return book;
        }                    

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325078053&siteId=291194637