C#二進(jìn)制流的序列化和反序列化操作-創(chuàng)新互聯(lián)

C#項(xiàng)目中較多使用了序列化和反序列化,較為常用的序列化和反序列化操作有二進(jìn)制流,JSON,XML等,現(xiàn)在介紹一下.net中二進(jìn)制流的序列化和反序列化操作方法:

創(chuàng)新互聯(lián)公司專注于古藺網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供古藺營銷型網(wǎng)站建設(shè),古藺網(wǎng)站制作、古藺網(wǎng)頁設(shè)計(jì)、古藺網(wǎng)站官網(wǎng)定制、微信小程序開發(fā)服務(wù),打造古藺網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供古藺網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。

1.將對象序列化為二進(jìn)制流:

        /// <summary>
        /// 將對象序列化為byte[]
        /// 使用IFormatter的Serialize序列化
        /// </summary>
        /// <param name="obj">需要序列化的對象</param>
        /// <returns>序列化獲取的二進(jìn)制流</returns>
        public static byte[] FormatterObjectBytes(object obj)
        {
            if(obj==null)
                throw new ArgumentNullException("obj");
            byte[] buff;
            try
            {
                using (var ms = new MemoryStream())
                {
                    IFormatter iFormatter = new BinaryFormatter();
                    iFormatter.Serialize(ms, obj);
                    buff = ms.GetBuffer();
                }
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }
            return buff;
        }

2.將對象轉(zhuǎn)為二進(jìn)制文件,并保存到指定的文件中:

 /// <summary>
        /// 將對象轉(zhuǎn)為二進(jìn)制文件,并保存到指定的文件中
        /// </summary>
        /// <param name="name">文件路徑</param>
        /// <param name="obj">待存的對象</param>
        /// <returns></returns>
        public static bool BinaryFileSave(string name,object obj)
        {
            Stream flstr=null;
            BinaryWriter binaryWriter=null;
            try
            {
                flstr = new FileStream(name, FileMode.Create);
                binaryWriter = new BinaryWriter(flstr);
                var buff = FormatterObjectBytes(obj);
                binaryWriter.Write(buff);
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }
            finally
            {
                if (binaryWriter != null) binaryWriter.Close();
                if (flstr != null) flstr.Close();
            }
            return true;
        }

3.將byte[]反序列化為對象:

        /// <summary>
        /// 將byte[]反序列化為對象
        /// 使用IFormatter的Deserialize發(fā)序列化
        /// </summary>
        /// <param name="buff">傳入的byte[]</param>
        /// <returns></returns>
        public static object FormatterByteObject(byte[] buff)
        {
            if(buff==null)
                throw new ArgumentNullException("buff");
            object obj;
            try
            {
                using (var ms = new MemoryStream())
                {
                    IFormatter iFormatter = new BinaryFormatter();
                    obj = iFormatter.Deserialize(ms);
                }
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }
            return obj;
        }

4.將對象序列化為byte[]:

        /// <summary>
        /// 將對象序列化為byte[]
        /// 使用Marshal的StructureToPtr序列化
        /// </summary>
        /// <param name="obj">需序列化的對象</param>
        /// <returns>序列化后的byte[]</returns>
        public static byte[] MarshalObjectByte(object obj)
        {
            if(obj==null)
                throw new ArgumentNullException("obj");
            byte[] buff;
            try
            {
                buff = new byte[Marshal.SizeOf(obj)];
                var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
                Marshal.StructureToPtr(obj, ptr, true);
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }
            return buff;
        }

5.將byte[]序列化為對象:

        /// <summary>
        /// 將byte[]序列化為對象
        /// </summary>
        /// <param name="buff">被轉(zhuǎn)換的二進(jìn)制流</param>
        /// <param name="type">轉(zhuǎn)換成的類名</param>
        /// <returns></returns>
        public static object MarshalByteObject(byte[] buff, Type type)
        {
            if(buff==null)
                throw new ArgumentNullException("buff");
            if(type==null)
                throw new ArgumentNullException("type");
            try
            {
                var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
                return Marshal.PtrToStructure(ptr, type);
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }
        }

6.將文件轉(zhuǎn)換為byte數(shù)組:

        /// <summary>
        /// 將文件轉(zhuǎn)換為byte數(shù)組
        /// </summary>
        /// <param name="path">文件地址</param>
        /// <returns>轉(zhuǎn)換后的byte[]</returns>
        public static byte[] FileObjectBytes(string path)
        {
            if(string.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");
            if (!File.Exists(path)) return new byte[0];
            try
            {
                var fi = new FileInfo(path);
                var buff = new byte[fi.Length];
                var fs = fi.OpenRead();
                fs.Read(buff, 0, Convert.ToInt32(fs.Length));
                fs.Close();
                return buff;
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }
        }

7.將byte[]轉(zhuǎn)換為文件并保存到指定的地址:

        /// <summary>
        /// 將byte[]轉(zhuǎn)換為文件并保存到指定的地址
        /// </summary>
        /// <param name="buff">需反序列化的byte[]</param>
        /// <param name="savePath">文件保存的路徑</param>
        /// <returns>是否成功</returns>
        public static string FileByteObject(byte[] buff, string savePath)
        {
            if(buff==null)
                throw new ArgumentNullException("buff");
            if(savePath==null)
                throw new ArgumentNullException("savePath");
            if (File.Exists(savePath)) return "文件名重復(fù)";
            try
            {
                var fs = new FileStream(savePath, FileMode.CreateNew);
                var bw = new BinaryWriter(fs);
                bw.Write(buff, 0, buff.Length);
                bw.Close();
                fs.Close();
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }
            return "保存成功";
        }

8.將圖片序列化為二進(jìn)制流:

        /// <summary>
        /// 將圖片序列化為二進(jìn)制流
        /// </summary>
        /// <param name="imgPath">圖片路徑</param>
        /// <returns>序列化后的二進(jìn)制流</returns>
        public static byte[] SetImgToBytes(string imgPath)
        {
            if(string.IsNullOrEmpty(imgPath))
                throw new ArgumentNullException(imgPath);
            try
            {
                byte[] byteData;
                using (var file=new FileStream(imgPath,FileMode.Open,FileAccess.Read))
                {
                    byteData=new byte[file.Length];
                    file.Read(byteData, 0, byteData.Length);
                    file.Close();
                }
                return byteData;
            }
            catch (Exception er)
            {
                
                throw new Exception(er.Message);
            }
        }

創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務(wù)器,動態(tài)BGP最優(yōu)骨干路由自動選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動現(xiàn)已開啟,新人活動云服務(wù)器買多久送多久。

本文題目:C#二進(jìn)制流的序列化和反序列化操作-創(chuàng)新互聯(lián)
瀏覽地址:http://muchs.cn/article32/dsoosc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)、網(wǎng)站改版、網(wǎng)站收錄外貿(mào)建站、建站公司、響應(yīng)式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)