C#项目中较多使用了序列化和反序列化,较为常用的序列化和反序列化操作有二进制流,JSON,XML等,现在介绍一下.net中二进制流的序列化和反序列化操作方法:
1.将对象序列化为二进制流:
/// <summary> /// 将对象序列化为byte[] /// 使用IFormatter的Serialize序列化 /// </summary> /// <param name="obj">需要序列化的对象</param> /// <returns>序列化获取的二进制流</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.将对象转为二进制文件,并保存到指定的文件中:
/// <summary> /// 将对象转为二进制文件,并保存到指定的文件中 /// </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发序列化 /// </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">被转换的二进制流</param> /// <param name="type">转换成的类名</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.将文件转换为byte数组:
/// <summary> /// 将文件转换为byte数组 /// </summary> /// <param name="path">文件地址</param> /// <returns>转换后的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[]转换为文件并保存到指定的地址:
/// <summary> /// 将byte[]转换为文件并保存到指定的地址 /// </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 "文件名重复"; 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.将图片序列化为二进制流:
/// <summary> /// 将图片序列化为二进制流 /// </summary> /// <param name="imgPath">图片路径</param> /// <returns>序列化后的二进制流</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); } }
创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。
本文题目:C#二进制流的序列化和反序列化操作-创新互联
浏览地址:https://www.cdcxhl.com/article32/dsoosc.html
成都网站建设公司_创新互联,为您提供定制开发、网站改版、网站收录、外贸建站、建站公司、响应式网站
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联