用C#进行Byte与文件的相互转换
工具类
using System;
using System.Collections.Generic;
using System.IO;
namespace Protocol
{
[Serializable]
public class FileBinaryConvertHelper
{
/// <summary>
/// 将文件转化位byte数组
/// </summary>
/// <param name="Path">文件地址</param>
/// <returns>转换为的byte数组</returns>
public static byte[] FileBytes(string Path)
{
if (!System.IO.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;
}
/// <summary>
/// 将byte数组转换为文件并保存到指定地址
/// </summary>
/// <param name="buff">byte数组</param>
/// <param name="savepath">保存地址</param>
public static void BytesFile(byte[] buff, string savepath)
{
if (System.IO.File.Exists(savepath))
{
System.IO.File.Delete(savepath);
}
FileStream fs = new FileStream(savepath, FileMode.CreateNew);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff, 0, buff.Length);
fs.Close();
}
}
}
入口
void Start()
{
//byte[] byteArray zip转化而来的字节数组 path1 保存路径
FileBinaryConvertHelper.BytesFile(byte[] byteArray, path1);//二进制数组转换为zip文件
UnityEngine.Debug.Log("转化 zip成功 ");
ZipFile.ExtractToDirectory(path1, path2);
UnityEngine.Debug.Log("解压 zip成功 +" );
}