object与byte[]的相互转换、文件与byte数组相互转换

object与byte[]的相互转换:

/// 
/// 工具类:对象与二进制流间的转换
/// 
class ByteConvertHelper
{
    /// 
    /// 将对象转换为byte数组
    /// 
    /// 被转换对象
    /// 转换后byte数组
    public static byte[] Object2Bytes(object obj)
    {
        byte[] buff;
        using (MemoryStream ms = new MemoryStream())
        {
            IFormatter iFormatter = new BinaryFormatter();
            iFormatter.Serialize(ms, obj);
            buff = ms.GetBuffer();
        }
        return buff;
    }

    /// 
    /// 将byte数组转换成对象
    /// 
    /// 被转换byte数组
    /// 转换完成后的对象
    public static object Bytes2Object(byte[] buff)
    {
        object obj;
        using (MemoryStream ms = new MemoryStream(buff))
        {
            IFormatter iFormatter = new BinaryFormatter();
            obj = iFormatter.Deserialize(ms);
        }
        return obj;
    }
}


文件与byte数组相互转换:

/// 
/// 工具类:文件与二进制流间的转换
/// 
class FileBinaryConvertHelper
{
    /// 
    /// 将文件转换为byte数组
    /// 
    /// 文件地址
    /// 转换后的byte数组
    public static byte[] File2Bytes(string path)
    {
        if(!File.Exists(path))
        {
            return new byte[0];
        }

        FileInfo fi = new FileInfo(path);
        byte[] buff = new byte[fi.Length];

        FileStream fs = fi.OpenRead();
        fs.Read(buff, 0, Convert.ToInt32(fs.Length));
        fs.Close();

        return buff;
    }

    /// 
    /// 将byte数组转换为文件并保存到指定地址
    /// 
    /// byte数组
    /// 保存地址
    public static void Bytes2File(byte[] buff, string savepath)
    {
        if (File.Exists(savepath))
        {
            File.Delete(savepath);
        }

        FileStream fs = new FileStream(savepath, FileMode.CreateNew);
        BinaryWriter bw = new BinaryWriter(fs);
        bw.Write(buff, 0, buff.Length);
        bw.Close();
        fs.Close();
    }
}

原文:http://my.oschina.net/Tsybius2014/blog/352409


新增,

Image与byte数组相互转换:

/// 
/// 从byte数组创建Image
/// 
public static Image Bytes2Image(byte[] bytes)
{
    System.IO.MemoryStream stream = new System.IO.MemoryStream();
    stream.Write(bytes, 0, bytes.Length);
    Image image = Image.FromStream(stream);

    return image;
}

/// 
/// 将Image转化为byte数组,使用缓存文件中转
/// 
public static byte[] Image2Bytes_tmpFile(Image image, ImageFormat imageFormat = null)
{
    if (imageFormat == null) imageFormat = ImageFormat.Jpeg;
    String tmpFilePath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.Ticks + ".stream";
    image.Save(tmpFilePath, imageFormat);   // 保存图像到文件

    byte[] bytes = File2Bytes(tmpFilePath); // 从文件中获取字节数组
    if (File.Exists(tmpFilePath)) File.Delete(tmpFilePath); //删除文件

    return bytes;
}





你可能感兴趣的:(C#,数据转换)