C#二进制流的序列化和反序列化操作
时间: 2023-09-04 18:11:16 浏览: 281
C#中可以使用二进制流进行对象的序列化和反序列化操作。对于序列化操作,可以使用IFormatter的Serialize方法将对象序列化为byte[]。具体的方法如下所示:
```
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 ex)
{
throw new Exception(ex.Message);
}
return buff;
}
```
而对于反序列化操作,则可以使用IFormatter的Deserialize方法将byte[]反序列化为对象。具体的方法如下所示:
```
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 ex)
{
throw new Exception(ex.Message);
}
return obj;
}
```
通过使用这两个方法,我们可以在C#中对对象进行二进制流的序列化和反序列化操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [C#二进制流的序列化和反序列化操作](https://blog.csdn.net/weixin_33923762/article/details/92329340)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文