需要将一些文件动态打包成 .zip 以创建 SCORM 包,有人知道如何使用代码来完成吗?是否也可以在 .zip 中动态构建文件夹结构?
9 回答
DotNetZip很适合这个。
您可以将 zip 直接写入 Response.OutputStream。代码如下所示:
Response.Clear();
Response.BufferOutput = false; // for large files...
System.Web.HttpContext c= System.Web.HttpContext.Current;
String ReadmeText= "Hello!\n\nThis is a README..." + DateTime.Now.ToString("G");
string archiveName= String.Format("archive-{0}.zip",
DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + archiveName);
using (ZipFile zip = new ZipFile())
{
// filesToInclude is an IEnumerable<String>, like String[] or List<String>
zip.AddFiles(filesToInclude, "files");
// Add a file from a string
zip.AddEntry("Readme.txt", "", ReadmeText);
zip.Save(Response.OutputStream);
}
// Response.End(); // no! See http://stackoverflow.com/questions/1087777
Response.Close();
DotNetZip 是免费的。
您不必再使用外部库了。System.IO.Packaging 具有可用于将内容放入 zip 文件的类。然而,它并不简单。 这是一个带有示例的博客文章(它在最后;挖掘它)。
该链接不稳定,因此这是 Jon 在帖子中提供的示例。
using System;
using System.IO;
using System.IO.Packaging;
namespace ZipSample
{
class Program
{
static void Main(string[] args)
{
AddFileToZip("Output.zip", @"C:\Windows\Notepad.exe");
AddFileToZip("Output.zip", @"C:\Windows\System32\Calc.exe");
}
private const long BUFFER_SIZE = 4096;
private static void AddFileToZip(string zipFilename, string fileToAdd)
{
using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
{
string destFilename = ".\\" + Path.GetFileName(fileToAdd);
Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
if (zip.PartExists(uri))
{
zip.DeletePart(uri);
}
PackagePart part = zip.CreatePart(uri, "",CompressionOption.Normal);
using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
{
using (Stream dest = part.GetStream())
{
CopyStream(fileStream, dest);
}
}
}
}
private static void CopyStream(System.IO.FileStream inputStream, System.IO.Stream outputStream)
{
long bufferSize = inputStream.Length < BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
long bytesWritten = 0;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0)
{
outputStream.Write(buffer, 0, bytesRead);
bytesWritten += bytesRead;
}
}
}
}
你可以看看SharpZipLib。这是一个示例。
如果您使用的是 .NET Framework 4.5 或更高版本,则可以避免使用第三方库并使用本System.IO.Compression.ZipArchive
机类。
这是一个使用 MemoryStream 和几个字节数组表示两个文件的快速代码示例:
byte[] file1 = GetFile1ByteArray();
byte[] file2 = GetFile2ByteArray();
using (MemoryStream ms = new MemoryStream())
{
using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
var zipArchiveEntry = archive.CreateEntry("file1.txt", CompressionLevel.Fastest);
using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(file1, 0, file1.Length);
zipArchiveEntry = archive.CreateEntry("file2.txt", CompressionLevel.Fastest);
using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(file2, 0, file2.Length);
}
return File(ms.ToArray(), "application/zip", "Archive.zip");
}
您可以在返回ActionResult
: 的 MVC 控制器中使用它,或者,如果您需要以物理方式创建 zip 存档,您可以将其保存MemoryStream
到磁盘或将其完全替换为FileStream
.
有关此主题的更多信息,您还可以阅读我博客上的这篇文章。
DotNetZip 非常易于使用... 在 ASP.Net 中创建 Zip 文件
为此,我使用了 chilkat 的免费组件:http: //www.chilkatsoft.com/zip-dotnet.asp。几乎完成了我需要的一切,但是我不确定动态构建文件结构。
能够使用 DotNetZip 做到这一点。您可以从 Visual Studio Nuget 包管理器或直接通过DotnetZip下载它。然后尝试下面的代码,
/// <summary>
/// Generate zip file and save it into given location
/// </summary>
/// <param name="directoryPath"></param>
public void CreateZipFile(string directoryPath )
{
//Select Files from given directory
List<string> directoryFileNames = Directory.GetFiles(directoryPath).ToList();
using (ZipFile zip = new ZipFile())
{
zip.AddFiles(directoryFileNames, "");
//Generate zip file folder into loation
zip.Save("C:\\Logs\\ReportsMyZipFile.zip");
}
}
如果要将文件下载到客户端,请使用以下代码。
/// <summary>
/// Generate zip file and download into client
/// </summary>
/// <param name="directoryPath"></param>
/// <param name="respnse"></param>
public void CreateZipFile(HttpResponse respnse,string directoryPath )
{
//Select Files from given directory
List<string> directoryFileNames = Directory.GetFiles(directoryPath).ToList();
respnse.Clear();
respnse.BufferOutput = false;
respnse.ContentType = "application/zip";
respnse.AddHeader("content-disposition", "attachment; filename=MyFiles.zip");
using (ZipFile zip = new ZipFile())
{
zip.CompressionLevel = CompressionLevel.None;
zip.AddFiles(directoryFileNames, "");
zip.Save(respnse.OutputStream);
}
respnse.flush();
}
使用我们的Rebex ZIP组件“即时”创建 ZIP 文件。
以下示例对其进行了完整描述,包括创建子文件夹:
// prepare MemoryStream to create ZIP archive within
using (MemoryStream ms = new MemoryStream())
{
// create new ZIP archive within prepared MemoryStream
using (ZipArchive zip = new ZipArchive(ms))
{
// add some files to ZIP archive
zip.Add(@"c:\temp\testfile.txt");
zip.Add(@"c:\temp\innerfile.txt", @"\subfolder");
// clear response stream and set the response header and content type
Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=sample.zip");
// write content of the MemoryStream (created ZIP archive) to the response stream
ms.WriteTo(Response.OutputStream);
}
}
// close the current HTTP response and stop executing this page
HttpContext.Current.ApplicationInstance.CompleteRequest();
#region Create zip file in asp.net c#
string DocPath1 = null;/*This varialble is Used for Craetting the File path .*/
DocPath1 = Server.MapPath("~/MYPDF/") + ddlCode.SelectedValue + "/" + txtYear.Value + "/" + ddlMonth.SelectedValue + "/";
string[] Filenames1 = Directory.GetFiles(DocPath1);
using (ZipFile zip = new ZipFile())
{
zip.AddFiles(Filenames, "Pdf");//Zip file inside filename
Response.Clear();
Response.BufferOutput = false;
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
Response.End();
}
#endregion