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

简介: /* - - - - - - - - - - - - - - - - - - - - - - - -  * Stream 和 byte[] 之间的转换 * - - - - - - - - - - - - - - - - - - - - - - - *//// /// 将 Stream 转成 byte...
/*  - - - - - - - - - - - - - - - - - - - - - - - - 
 * 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;
}
目录
相关文章
|
Java .NET API
Java8的stream API与 C#的 LINQ 拓展方法对比
原文:https://www.zeusro.tech/2018/03/08/linq-vs-stream/
3330 0
|
安全 C# 数据安全/隐私保护
使用C# (.NET Core) 实现装饰模式 (Decorator Pattern) 并介绍 .NET/Core的Stream
该文章综合了几本书的内容. 某咖啡店项目的解决方案 某咖啡店供应咖啡, 客户买咖啡的时候可以添加若干调味料, 最后要求算出总价钱. Beverage是所有咖啡饮料的抽象类, 里面的cost方法是抽象的.
1364 0
|
C# 数据安全/隐私保护
c#常见stream操作
原文: c#常见stream操作   常见并常用的stream一共有 文件流(FileStream), 内存流(MemoryStream), 压缩流(GZipStream), 加密流(CrypToStream), 网络流(NetworkStream); 1.
1533 0
|
C#
C# Stream 和 byte[] 之间的转换
原文:C# Stream 和 byte[] 之间的转换 Stream 和 byte[] 之间的转换   /* - - - - - - - - - - - - - - - - - - - - - - - - * Stream 和 byte[] 之间的转换 * - - - - - - - - - ...
845 0
silverlight中如何将BitmapImage转化为Stream或byte数组?
上一篇"base64编码在silverlight中的使用"里已经提到WriteableBitmap对象可以借助FluxJpeg转化为base64字符串,而WriteableBitmap又能从BitmapSource直接构造,so .
1094 0