stream 、 string 、byte[] 间的相互转换 扩展方法

忘是亡心i 2024-02-17 23:21 121阅读 0赞

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;

namespace Ims.Bll
{
///


/// stream 、 string 、byte[] 间的转换扩展方法类
///

public static class StreamExtend
{
#region Stream 扩展
///
/// Stream Stream 转换为 byte 数组
///

///
public static byte[] ToByteArray(this Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
///
/// Stream 转换为 image 图片
///

///
public static Image ToImage(this Stream stream)
{
Image img = new Bitmap(stream);
return img;
}
///
/// Stream 转换为 string ,使用 Encoding.Default 编码
///

///
public static string ToStr(this Stream stream)
{
return System.Text.Encoding.Default.GetString(stream.ToByteArray());
}
#endregion

#region byte[] 扩展
///


/// byte[] 转换为 stream 流
///

///
public static Stream ToStream(this byte[] arr)
{
Stream stream = new MemoryStream(arr);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
return stream;
}
///
/// byte[] 转换为 Image
///

///
public static Image ToImage(this byte[] arr)
{
return Image.FromStream(arr.ToStream());
}
///
/// 转换为 string,使用 Encoding.Default 编码
///

///
public static string ToStr(this byte[] arr)
{
return System.Text.Encoding.Default.GetString(arr);
}
#endregion

#region string 扩展
///


/// string 转换为 byte[]
///

///
public static byte[] ToByteArray(this string str)
{
return System.Text.Encoding.Default.GetBytes(str);
}
///
/// string 转换为 Stream
///

///
public static Stream ToStream(this string str)
{
Stream stream = new MemoryStream(str.ToByteArray());
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
return stream;
}
#endregion
}
}

-———————————————————————

//测试代码

int sourceLength = 0; //数据源长度
long byteArrLength = 0; //byte[] 的长度
long streamLength = 0; //Stream 的长度
// char 类型
char c = ‘A’;
byte[] byteArr_c = c.ToString().ToByteArray();
Stream sm_c = c.ToString().ToStream();
sourceLength = 1;
byteArrLength = byteArr_c.Length;
streamLength = sm_c.Length;

//string 类型
string str = “ABCDEF”;
byte[] byteArr_str = str.ToByteArray();
Stream sm_str = str.ToStream();
sourceLength = str.Length;
byteArrLength = byteArr_str.Length;
streamLength = sm_str.Length;

//汉字
string cn = “好”;
byte[] byteArr_cn = cn.ToByteArray();
Stream sm_cn = str.ToStream();
sourceLength = cn.Length;
byteArrLength = byteArr_cn.Length;
streamLength = sm_cn.Length;

char cn_l = (char)byteArr_cn[0];
char cn_r = (char)byteArr_cn[1];

技术支持:http://blog.csdn.net/xxj\_jing

对于上面的代码 http://blog.csdn.net/xxj_jing/article/details/7514046 里进行了部分扩展,支持了 stream和byte 的搜索、查找方法!

发表评论

表情:
评论列表 (有 0 条评论,121人围观)

还没有评论,来说两句吧...

相关阅读