C#二进制流的序列化和反序列化

  1  public class BinaryHelper
  2     {
  3         /// <summary>
  4         /// 将对象序列化为byte[]
  5         /// 使用IFormatter的Serialize序列化
  6         /// </summary>
  7         /// <param name="obj">需要序列化的对象</param>
  8         /// <returns>序列化获取的二进制流</returns>
  9         public static byte[] FormatterObjectBytes(object obj)
 10         {
 11             if(obj==null)
 12                 throw new ArgumentNullException("obj");
 13             byte[] buff;
 14             try
 15             {
 16                 using (var ms = new MemoryStream())
 17                 {
 18                     IFormatter iFormatter = new BinaryFormatter();
 19                     iFormatter.Serialize(ms, obj);
 20                     buff = ms.GetBuffer();
 21                 }
 22             }
 23             catch (Exception er)
 24             {
 25                 throw new Exception(er.Message);
 26             }
 27             return buff;
 28         }
 29 
 30 
 31         /// <summary>
 32         /// 将对象转为二进制文件,并保存到指定的文件中
 33         /// </summary>
 34         /// <param name="name">文件路径</param>
 35         /// <param name="obj">待存的对象</param>
 36         /// <returns></returns>
 37         public static bool BinaryFileSave(string name,object obj)
 38         {
 39             Stream flstr=null;
 40             BinaryWriter binaryWriter=null;
 41             try
 42             {
 43                 flstr = new FileStream(name, FileMode.Create);
 44                 binaryWriter = new BinaryWriter(flstr);
 45                 var buff = FormatterObjectBytes(obj);
 46                 binaryWriter.Write(buff);
 47             }
 48             catch (Exception er)
 49             {
 50                 throw new Exception(er.Message);
 51             }
 52             finally
 53             {
 54                 if (binaryWriter != null) binaryWriter.Close();
 55                 if (flstr != null) flstr.Close();
 56             }
 57             return true;
 58         }
 59 
 60         /// <summary>
 61         /// 将byte[]反序列化为对象
 62         /// 使用IFormatter的Deserialize发序列化
 63         /// </summary>
 64         /// <param name="buff">传入的byte[]</param>
 65         /// <returns></returns>
 66         public static object FormatterByteObject(byte[] buff)
 67         {
 68             if(buff==null)
 69                 throw new ArgumentNullException("buff");
 70             object obj;
 71             try
 72             {
 73                 using (var ms = new MemoryStream())
 74                 {
 75                     IFormatter iFormatter = new BinaryFormatter();
 76                     obj = iFormatter.Deserialize(ms);
 77                 }
 78             }
 79             catch (Exception er)
 80             {
 81                 throw new Exception(er.Message);
 82             }
 83             return obj;
 84         }
 85 
 86 
 87         /// <summary>
 88         /// 将对象序列化为byte[]
 89         /// 使用Marshal的StructureToPtr序列化
 90         /// </summary>
 91         /// <param name="obj">需序列化的对象</param>
 92         /// <returns>序列化后的byte[]</returns>
 93         public static byte[] MarshalObjectByte(object obj)
 94         {
 95             if(obj==null)
 96                 throw new ArgumentNullException("obj");
 97             byte[] buff;
 98             try
 99             {
100                 buff = new byte[Marshal.SizeOf(obj)];
101                 var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
102                 Marshal.StructureToPtr(obj, ptr, true);
103             }
104             catch (Exception er)
105             {
106                 throw new Exception(er.Message);
107             }
108             return buff;
109         }
110 
111         /// <summary>
112         /// 将byte[]序列化为对象
113         /// </summary>
114         /// <param name="buff">被转换的二进制流</param>
115         /// <param name="type">转换成的类名</param>
116         /// <returns></returns>
117         public static object MarshalByteObject(byte[] buff, Type type)
118         {
119             if(buff==null)
120                 throw new ArgumentNullException("buff");
121             if(type==null)
122                 throw new ArgumentNullException("type");
123             try
124             {
125                 var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
126                 return Marshal.PtrToStructure(ptr, type);
127             }
128             catch (Exception er)
129             {
130                 throw new Exception(er.Message);
131             }
132         }
133 
134 
135         /// <summary>
136         /// 将文件转换为byte数组
137         /// </summary>
138         /// <param name="path">文件地址</param>
139         /// <returns>转换后的byte[]</returns>
140         public static byte[] FileObjectBytes(string path)
141         {
142             if(string.IsNullOrEmpty(path))
143                 throw new ArgumentNullException("path");
144             if (!File.Exists(path)) return new byte[0];
145             try
146             {
147                 var fi = new FileInfo(path);
148                 var buff = new byte[fi.Length];
149                 var fs = fi.OpenRead();
150                 fs.Read(buff, 0, Convert.ToInt32(fs.Length));
151                 fs.Close();
152                 return buff;
153             }
154             catch (Exception er)
155             {
156                 throw new Exception(er.Message);
157             }
158         }
159 
160 
161         /// <summary>
162         /// 将byte[]转换为文件并保存到指定的地址
163         /// </summary>
164         /// <param name="buff">需反序列化的byte[]</param>
165         /// <param name="savePath">文件保存的路径</param>
166         /// <returns>是否成功</returns>
167         public static string FileByteObject(byte[] buff, string savePath)
168         {
169             if(buff==null)
170                 throw new ArgumentNullException("buff");
171             if(savePath==null)
172                 throw new ArgumentNullException("savePath");
173             if (File.Exists(savePath)) return "文件名重复";
174             try
175             {
176                 var fs = new FileStream(savePath, FileMode.CreateNew);
177                 var bw = new BinaryWriter(fs);
178                 bw.Write(buff, 0, buff.Length);
179                 bw.Close();
180                 fs.Close();
181             }
182             catch (Exception er)
183             {
184                 throw new Exception(er.Message);
185             }
186             return "保存成功";
187         }
188 
189 
190         /// <summary>
191         /// 将图片序列化为二进制流
192         /// </summary>
193         /// <param name="imgPath">图片路径</param>
194         /// <returns>序列化后的二进制流</returns>
195         public static byte[] SetImgToBytes(string imgPath)
196         {
197             if(string.IsNullOrEmpty(imgPath))
198                 throw new ArgumentNullException(imgPath);
199             try
200             {
201                 byte[] byteData;
202                 using (var file=new FileStream(imgPath,FileMode.Open,FileAccess.Read))
203                 {
204                     byteData=new byte[file.Length];
205                     file.Read(byteData, 0, byteData.Length);
206                     file.Close();
207                 }
208                 return byteData;
209             }
210             catch (Exception er)
211             {
212                 
213                 throw new Exception(er.Message);
214             }
215         }
216 
217 
218 
219     }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏我和未来有约会

简练的视图模型 ViewModel

patterns & practices Developer Center 发布了 Unity Application Block 1.2 for Silver...

2349
来自专栏码匠的流水账

聊聊HystrixThreadPool

hystrix-core-1.5.12-sources.jar!/com/netflix/hystrix/HystrixThreadPool.java

921
来自专栏跟着阿笨一起玩NET

c# 使用timer定时器操作,上次定时到了以后,下次还未执行完怎么处理

------解决方案-------------------------------------------------------- 开始的时候,禁用定时器,你...

3041
来自专栏码匠的流水账

聊聊HystrixCommandExecutionHook

hystrix-core-1.5.12-sources.jar!/com/netflix/hystrix/strategy/executionhook/Hyst...

832
来自专栏码匠的流水账

聊聊spring cloud的HystrixAutoConfiguration

本文主要研究一下spring cloud的HystrixAutoConfiguration

1122
来自专栏linux驱动个人学习

ALSA声卡驱动的DAPM(一)-DPAM详解

最近使用tinymix 调试相应的音频通道,但是一直不知道音频通道的原理是什么。所以百度了一下,百度结果是与DPAM有关。 一、DAPM简介:  DAPM是Dy...

5146
来自专栏一个会写诗的程序员的博客

java.base.jmod

/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/jmods$ jmod list java....

1182
来自专栏Pulsar-V

Save Camera Document

#pragma once #include "HCCamera.h" #include <time.h> #include <cstdio> #incl...

2908
来自专栏专知

2018年SCI期刊最新影响因子排行,最高244,人工智能TPAMI9.455

2018年6月26日,最新的SCI影响因子正式发布,涵盖1万2千篇期刊。CA-Cancer J Clin 依然拔得头筹,其影响因子今年再创新高,达244.585...

1482
来自专栏Hadoop数据仓库

Oracle sqlldr 如何导入一个日期列

1. LOAD DATA INFILE * INTO TABLE test FIELDS TERMINATED BY X'9' TRAILING NULLCO...

1876

扫码关注云+社区