C# 对象、文件与byte数组之间的转换
标签:time result bin stream sizeof turn 转换 top files
1.使用Marshal类的StructureToPtr与PtrToStructure函数对object与byte数组进行转换
命名空间:System.Runtime.InteropServices
///
/// 将对象转换为byte数组
///
/// 被转换对象
/// 转换后byte数组
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;
}
///
/// 将byte数组转换成对象
///
/// 被转换byte数组
/// 转换成的类名
/// 转换完成后的对象
public static object BytesToObject(byte[] buff, Type type)
{
IntPtr intPtr = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
return Marshal.PtrToStructure(intPtr, type);
}
2.使用FileStream将文件与byte数组相互转换
命名空间:System.IO
///
/// 将文件转换为byte数组
///
/// 文件地址
/// 转换后的byte数组
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;
}
///
/// 将byte数组转换为文件并保存到指定地址
///
/// byte数组
/// 保存地址
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
评论