[英]How to merge multiple XML files with data in same format in it to a single XML file with all data together using C#.NET?
[英]How do I merge several different files into a single file with custome file type using c#.net?
我需要将多个文件(视频,音乐和文本)组合成具有自定义文件类型(例如*.abcd
)和自定义文件数据结构的单个文件,并且该文件只能由我的程序读取,而我的程序应为能够分隔此文件的各个部分。 如何在.net
和c#
执行此操作?
https://www.imageupload.co.uk/image/ZWnh
就像M463正确指出的那样,您可以使用System.IO.Compression
将这些文件压缩在一起并对其进行加密...尽管加密是一门完全不同的技巧,但又令人头疼。
更好的选择是在文件的前几个字节中包含一些元数据,然后将文件的字节存储为原始字节。 这样可以避免任何人仅通过在文本编辑器中查看内容来确定内容。 同样,如果您想真正保护数据,则不可避免地要进行加密。 但是开始的简单算法是:
using System;
using System.IO;
using System.Collections.Generic;
namespace Compression
{
public class ClassName
{
public static void Compress(string[] fileNames, string resultantFileName)
{
List<byte> bytesToWrite = new List<byte>();
//add metadata about the number of files
int filesLength = fileNames.Length;
bytesToWrite.AddRange(BitConverter.GetBytes(filesLength));
List<byte[]> files = new List<byte[]>();
foreach(string fileName in fileNames)
{
byte[] bytes = File.ReadAllBytes(fileName);
//add metadata about the size of each file
bytesToWrite.AddRange(BitConverter.GetBytes(bytes.Length));
files.Add(bytes);
}
foreach(byte[] bytes in files)
{
//write the actual files itself
bytesToWrite.AddRange(bytes);
}
File.WriteAllBytes(resultantFileName, bytesToWrite.ToArray());
}
public static void Decompress(string fileName)
{
List<byte> bytes = new List<byte>(File.ReadAllBytes(fileName));
//this int represents the number of files in the byte array
int filesLength = BitConverter.ToInt32(bytes.ToArray(), 0);
List<int> sizes = new List<int>();
//get the size of each file
for(int i = 0; i < filesLength; i++)
{
//the first 2 bytes represent the number of files
//then each succeding int represents the size of each file
int size = BitConverter.ToInt32(bytes.ToArray(), 2 + i * 2);
sizes.Add(size);
}
//now read all the files
for(int i = 0; i < filesLength; i++)
{
int lastByteTillNow = 0;
for(int j = 0; j < i; j++)
lastByteTillNow += sizes[j];
File.WriteAllBytes("file " + i, bytes.GetRange(2 + 2 * filesLength + lastByteTillNow, sizes[i]).ToArray());
}
}
}
}
现在显然这不是您遇到的最佳算法,也不是最优化的代码片段。 毕竟,这正是我能在10-15分钟内得出的结果。 所以我还没有测试过。 但是,关键是,它给您带来了灵感,不是吗? 我已经将每个文件的大小限制为Int32
的最大长度(但是,将其更改为Int64
又名long
不会很麻烦)。 但这给你一个主意。 您甚至可以修改代码段,以通过MemoryStreams(我认为是Systtem.IO.MemorySteam
)在RAM中进行加载和写入。 但是,无论如何,这应该给您一个开始!
包含文件的加密的.zip容器如何? .NET框架中已经可以处理.zip文件,请查看System.IO.Compression
命名空间。 或者,您可以使用一些第三方库。
如果您确实要...,甚至可以通过重命名文件来强制使用其他文件扩展名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.