码迷,mamicode.com
首页 > 编程语言 > 详细

C# 对象、文件与byte数组之间的转换

时间:2020-12-30 10:46:02      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:time   result   bin   stream   sizeof   turn   转换   top   files   

1.使用Marshal类的StructureToPtr与PtrToStructure函数对object与byte数组进行转换

命名空间:System.Runtime.InteropServices

    /// <summary>
    /// 将对象转换为byte数组
    /// </summary>
    /// <param name="obj">被转换对象</param>
    /// <returns>转换后byte数组</returns>
    public static byte[] ObjectToBytes(object obj)
    {
        byte[] result = new byte[Marshal.SizeOf(obj)];
        IntPtr intPtr = Marshal.UnsafeAddrOfPinnedArrayElement(result, 0);
        Marshal.StructureToPtr(obj, intPtr, true);
        return result;
    }

    /// <summary>
    /// 将byte数组转换成对象
    /// </summary>
    /// <param name="buff">被转换byte数组</param>
    /// <param name="type">转换成的类名</param>
    /// <returns>转换完成后的对象</returns>
    public static object BytesToObject(byte[] buff, Type type)
    {
        IntPtr intPtr = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
        return Marshal.PtrToStructure(intPtr, type);
    }

2.使用FileStream将文件与byte数组相互转换

命名空间:System.IO

    /// <summary>
    /// 将文件转换为byte数组
    /// </summary>
    /// <param name="path">文件地址</param>
    /// <returns>转换后的byte数组</returns>
    public static byte[] File2Bytes(string path)
    {
        if (!File.Exists(path))
        {
            return new byte[0];
        }

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

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

        return buff;
    }

    /// <summary>
    /// 将byte数组转换为文件并保存到指定地址
    /// </summary>
    /// <param name="buff">byte数组</param>
    /// <param name="savepath">保存地址</param>
    public static void BytesToFile(byte[] buff, string savePath)
    {
        if (File.Exists(savePath))
        {
            File.Delete(savePath);
        }

        FileStream fileStream = new FileStream(savePath, FileMode.CreateNew);
        BinaryWriter binaryWriter = new BinaryWriter(fileStream);
        binaryWriter.Write(buff, 0, buff.Length);
        binaryWriter.Close();
        fileStream.Close();
    }

C# 对象、文件与byte数组之间的转换

标签:time   result   bin   stream   sizeof   turn   转换   top   files   

原文地址:https://www.cnblogs.com/Drock/p/14185654.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!