Copy a object by content,not by reference : File MemoryStream « File Stream « C# / C Sharp






Copy a object by content,not by reference

 

//http://tinyerp.codeplex.com/
//GNU Library General Public License (LGPL)
//-----------------------------------------------------------------------
// <copyright file="SysUtil.cs" company="Pyramid Consulting">
//     Copyright (c) Pyramid Consulting. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;

namespace Bamboo.Core.Common
{
    public class SysUtil
    {

        /// <summary>
        /// copy a object by content,not by reference
        /// </summary>
        /// <typeparam name="T">type of object</typeparam>
        /// <param name="srcObject">source objected to be cloned</param>
        /// <returns>the object that cloned from the source object</returns>
        public static T SerializeClone<T>(T srcObject)
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bfFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.MemoryStream msStream = new System.IO.MemoryStream();
            T result = default(T);
            try
            {
                bfFormatter.Serialize(msStream, srcObject);
                msStream.Seek(0, System.IO.SeekOrigin.Begin);
                result=(T)bfFormatter.Deserialize(msStream);
            }
            finally
            {
                if (msStream != null) msStream.Close();
            }
            return result;
        }
    }
}

   
  








Related examples in the same category

1.Demonstrate MemoryStreamDemonstrate MemoryStream
2.illustrates use of MemoryStreams
3.Demonstrates reading a file into memory, attaching it to a MemoryStream and using stream methods to access the contents