C# 文件合并与还原

来源:互联网 发布:linux echo的用法 编辑:程序博客网 时间:2024/06/05 22:39

 在工作要用到几个文件合并在一起打包 然后在另外一个C/S 上面来获取解析合并这几个文件,想到用压缩的做法 貌似要需要很多api 刚好参照T-L-V格式的方式自定义个类似的规格在合并及还原文件。

   F-文件标识 N-文件名字标识 L-文件名字所占用的长度 Value- 文件名称内容    C-文件内容标识 L-长度 Value-文件内容


文件合并转换成byte数组

 

  static List<byte> FileToBytes(IEnumerable<string> paths)        {            List<byte> lists = new List<byte>();            foreach (var item in paths)            {                string name = item.Substring(item.LastIndexOf("\\") + 1);                byte[] arr = Encoding.UTF8.GetBytes(name);                lists.Add(70); //F                lists.Add(78); //N                byte[] nameLens = BitConverter.GetBytes(arr.Length);                lists.AddRange(nameLens);                lists.AddRange(arr);                lists.Add(67); //C                byte[] fileC = File.ReadAllBytes(item);                byte[] flens = BitConverter.GetBytes(fileC.LongLength);                lists.AddRange(flens);                lists.AddRange(fileC);                lists.Add(69);  //E            }            return lists;        }



 static void BytesToFiles(List<byte> list)        {            long len = list.LongCount();            int index = 0;            byte[] byteNLen = new byte[4];  //文件名长度            byte[] byteCLen = new byte[8];  //文件内容            List<byte> listName = new List<byte>();            while (index <= len)            {                index += 2;                if (index > len)                    return;                listName.Clear();                list.CopyTo((int)index, byteNLen, 0, 4);                index += 4;                int nameLen = BitConverter.ToInt32(byteNLen, 0);                listName.AddRange(list.Skip(index).Take(nameLen));                string fileName = Encoding.UTF8.GetString(listName.ToArray());                index += nameLen;                index++;                list.CopyTo((int)index, byteCLen, 0, 8);                index += 8;                int contentLen = (int)BitConverter.ToInt64(byteCLen, 0);                byte[] content = list.Skip(index).Take(contentLen).ToArray();                index += (contentLen + 1);                File.WriteAllBytes("e:\\test\\" + fileName, content);            }        }


0 0
原创粉丝点击