手机
当前位置:查字典教程网 >编程开发 >C#教程 >C# Stream 和 byte[] 之间的转换
C# Stream 和 byte[] 之间的转换
摘要:/*------------------------*Stream和byte[]之间的转换*-----------------------*...

/*------------------------

*Stream和byte[]之间的转换

*-----------------------*/

///<summary>

///将Stream转成byte[]

///</summary>

publicbyte[]StreamToBytes(Streamstream)

{

byte[]bytes=newbyte[stream.Length];

stream.Read(bytes,0,bytes.Length);

//设置当前流的位置为流的开始

stream.Seek(0,SeekOrigin.Begin);

returnbytes;

}

///<summary>

///将byte[]转成Stream

///</summary>

publicStreamBytesToStream(byte[]bytes)

{

Streamstream=newMemoryStream(bytes);

returnstream;

}

/*------------------------

*Stream和文件之间的转换

*-----------------------*/

///<summary>

///将Stream写入文件

///</summary>

publicvoidStreamToFile(Streamstream,stringfileName)

{

//把Stream转换成byte[]

byte[]bytes=newbyte[stream.Length];

stream.Read(bytes,0,bytes.Length);

//设置当前流的位置为流的开始

stream.Seek(0,SeekOrigin.Begin);

//把byte[]写入文件

FileStreamfs=newFileStream(fileName,FileMode.Create);

BinaryWriterbw=newBinaryWriter(fs);

bw.Write(bytes);

bw.Close();

fs.Close();

}

///<summary>

///从文件读取Stream

///</summary>

publicStreamFileToStream(stringfileName)

{

//打开文件

FileStreamfileStream=newFileStream(fileName,FileMode.Open,FileAccess.Read,FileShare.Read);

//读取文件的byte[]

byte[]bytes=newbyte[fileStream.Length];

fileStream.Read(bytes,0,bytes.Length);

fileStream.Close();

//把byte[]转换成Stream

Streamstream=newMemoryStream(bytes);

returnstream;

}

【C# Stream 和 byte[] 之间的转换】相关文章:

C# DataGridView添加新行的2个方法

C# BackgroundWorker组件学习入门介绍

C#中fixed关键字的作用总结

C# WinForm程序完全退出的问题解决

C#常用的数据格式转换汇总

ref与out之间的区别深入解析

c# 自定义泛型链表类的详解

C#枚举数值与名称的转换实例分享

C#中StringBuilder用法以及和String的区别分析

C# char类型字符转换大小写的实现代码

精品推荐
分类导航