所以我基本上拥有的是一堆存储在数据库中的文件,我想要提取和压缩。我想做的一件事就是在记忆中做到这一点。
我想将此作为电子邮件附件发送。
基本上是这样的:
我已经完成了1和4,但是如何在内存中创建一个文件数组?当我从数据库中尝试文件时,数据在byte []中,文件名是一个字符串。
有什么想法吗?
答案 0 :(得分:0)
如果我正确理解你的问题,就像这样:
class FileToZip
{
public string fileName { get; set; }
public byte[] data { get; set; }
}
然后
var listOfFile = new List<FileToZip>();
或
var arrayOfFile = new FileToZip[numberOfFiles];
Zip库应该有说明如何将这些信息放入zip文件。
答案 1 :(得分:0)
当您将文件作为字节数组(或内存流)获取时,可以使用.NET ZipArchive类将文件写入ZIP文件。
class ZipFile
{
public string Name { get; set; }
public byte[] Data { get; set; }
}
...
var files = new List<ZipFile>(); //The files to zip
var zipStream = new MemoryStream(); //Where the zip archive is stored
using (var zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Create))
{
foreach (var file in files)
{
var fileEntry = zipArchive.CreateEntry(file.Name);
using (var entryStream = fileEntry.Open())
{
entryStream.Write(file.Data, 0, file.Data.Length);
}
}
}
//You can now send the zip archive as binary data.
答案 2 :(得分:-1)
您可以使用System.IO.Compression中的ZipArchive类完成此操作。 http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive(v=vs.110).aspx
以下是一个例子:
// Test data representing what you pulled from the database in #1
string file1Name = "Hello.txt";
byte[] file1Data = Encoding.UTF8.GetBytes("Hello World");
// Open a new .zip file
using (FileStream stream = new FileStream(@"my.zip", FileMode.Create))
using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Update))
{
// Add each item to the zip file. Loop this if you have multiple
ZipArchiveEntry readmeEntry = archive.CreateEntry(file1Name);
using (BinaryWriter writer = new BinaryWriter(readmeEntry.Open()))
{
writer.Write(file1Data);
}
}
这将创建一个名为my.zip的文件,其中包含一个名为Hello.txt的文件。 My.zip将在您的输出文件夹中。