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

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#调用系统打印机和收银钱箱(USB或虚拟USB端口链接的打印机)


下一篇:Java标识符和关键字