C# Stream 和 byte[] 之间的转换

简介:

http://www.jb51.net/article/13706.htm

 

复制代码
/*  - - - - - - - - - - - - - - - - - - - - - - - - 
* Stream 和 byte[] 之间的转换 
* - - - - - - - - - - - - - - - - - - - - - - - 
*/  
///   <summary>  
///  将 Stream 转成 byte[] 
///   </summary>  
public   byte [] StreamToBytes(Stream stream) 

byte [] bytes  =   new   byte [stream.Length]; 
stream.Read(bytes, 
0 , bytes.Length); 

//  设置当前流的位置为流的开始 
stream.Seek( 0 , SeekOrigin.Begin); 
return  bytes; 


///   <summary>  
///  将 byte[] 转成 Stream 
///   </summary>  
public  Stream BytesToStream( byte [] bytes) 

Stream stream 
=   new  MemoryStream(bytes); 
return  stream; 



/*  - - - - - - - - - - - - - - - - - - - - - - - - 
* Stream 和 文件之间的转换 
* - - - - - - - - - - - - - - - - - - - - - - - 
*/  
///   <summary>  
///  将 Stream 写入文件 
///   </summary>  
public   void  StreamToFile(Stream stream, string  fileName) 

//  把 Stream 转换成 byte[] 
byte [] bytes  =   new   byte [stream.Length]; 
stream.Read(bytes, 
0 , bytes.Length); 
//  设置当前流的位置为流的开始 
stream.Seek( 0 , SeekOrigin.Begin); 

//  把 byte[] 写入文件 
FileStream fs  =   new  FileStream(fileName, FileMode.Create); 
BinaryWriter bw 
=   new  BinaryWriter(fs); 
bw.Write(bytes); 
bw.Close(); 
fs.Close(); 


///   <summary>  
///  从文件读取 Stream 
///   </summary>  
public  Stream FileToStream( string  fileName) 

//  打开文件 
FileStream fileStream  =   new  FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); 
//  读取文件的 byte[] 
byte [] bytes  =   new   byte [fileStream.Length]; 
fileStream.Read(bytes, 
0 , bytes.Length); 
fileStream.Close(); 
//  把 byte[] 转换成 Stream 
Stream stream  =   new  MemoryStream(bytes); 
return  stream; 


复制代码

 

 

本文转自火地晋博客园博客,原文链接:http://www.cnblogs.com/yelaiju/archive/2010/09/18/1829858.html,如需转载请自行联系原作者

目录
相关文章
|
C#
C# Stream 和 byte[] 之间的转换
原文:C# Stream 和 byte[] 之间的转换 Stream 和 byte[] 之间的转换   /* - - - - - - - - - - - - - - - - - - - - - - - - * Stream 和 byte[] 之间的转换 * - - - - - - - - - ...
833 0
|
C#
C# Stream 和 byte[] 之间的转换
/* - - - - - - - - - - - - - - - - - - - - - - - -  * Stream 和 byte[] 之间的转换 * - - - - - - - - - - - - - - - - - - - - - - - *//// /// 将 Stream 转成 byte...
896 0
silverlight中如何将BitmapImage转化为Stream或byte数组?
上一篇"base64编码在silverlight中的使用"里已经提到WriteableBitmap对象可以借助FluxJpeg转化为base64字符串,而WriteableBitmap又能从BitmapSource直接构造,so .
1065 0
|
5月前
|
Java
java 读取文件 获取byte[]字节 并执行Gzip的压缩和解压
java 读取文件 获取byte[]字节 并执行Gzip的压缩和解压
49 0
|
8月前
|
存储 Java 计算机视觉
java 之byte
当涉及到处理数据时,Java 提供了多种数据类型,其中包括 `byte` 类型。在本文中,我们将深入探讨 Java 中的 `byte` 数据类型,了解它的特点、用途以及在编程中的实际应用。
|
8月前
|
Java
Java中 String与基本数据类型,包装类,char[],byte[]之间的转换
Java中 String与基本数据类型,包装类,char[],byte[]之间的转换
56 0
|
10月前
|
存储 Java
[java 基础知识] byte int 互转
[java 基础知识] byte int 互转
99 0