本文整理汇总了C#中ZipFile类的典型用法代码示例。如果您正苦于以下问题:C# ZipFile类的具体用法?C# ZipFile怎么用?C# ZipFile使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ZipFile类属于命名空间,在下文中一共展示了ZipFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Serialize
/// <summary>
/// Serialize
/// </summary>
/// <param name="site">site</param>
/// <param name="path">path</param>
/// <returns></returns>
public void Serialize(Site site, string path)
{
if (site == null)
{
throw new ArgumentException("site");
}
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentException("stream");
}
var tempPath = Path.GetTempPath() + "site.xml";
using (var stream = File.Create(tempPath))
{
var serializer = new XmlSerializer(typeof(Site));
serializer.Serialize(stream, site);
}
var packagePath = path + Path.DirectorySeparatorChar + site.Name + ".wbp";
if (File.Exists(packagePath))
{
File.Delete(packagePath);
}
using (ZipFile package = new ZipFile(packagePath, Console.Out))
{
package.AddFile(tempPath, string.Empty);
package.AddFiles(site.Resources.Select(r => r.TextData).Where(File.Exists), "resources");
package.Save();
}
}
示例2: CompressFolder
static public void CompressFolder(string aFolderName, string aFullFileOuputName, string[] ExcludedFolderNames, string[] ExcludedFileNames){
// Perform some simple parameter checking. More could be done
// like checking the target file name is ok, disk space, and lots
// of other things, but for a demo this covers some obvious traps.
if (!Directory.Exists(aFolderName)) {
Debug.Log("Cannot find directory : " + aFolderName);
return;
}
try
{
string[] exFileNames = new string[0];
string[] exFolderNames = new string[0];
if(ExcludedFileNames != null) exFileNames = ExcludedFileNames;
if(ExcludedFolderNames != null) exFolderNames = ExcludedFolderNames;
// Depending on the directory this could be very large and would require more attention
// in a commercial package.
List<string> filenames = GenerateFolderFileList(aFolderName, null);
//foreach(string filename in filenames) Debug.Log(filename);
// 'using' statements guarantee the stream is closed properly which is a big source
// of problems otherwise. Its exception safe as well which is great.
using (ZipOutputStream zipOut = new ZipOutputStream(File.Create(aFullFileOuputName))){
zipOut.Finish();
zipOut.Close();
}
using(ZipFile s = new ZipFile(aFullFileOuputName)){
s.BeginUpdate();
int counter = 0;
//add the file to the zip file
foreach(string filename in filenames){
bool include = true;
string entryName = filename.Replace(aFolderName, "");
//Debug.Log(entryName);
foreach(string fn in exFolderNames){
Regex regEx = new Regex(@"^" + fn.Replace(".",@"\."));
if(regEx.IsMatch(entryName)) include = false;
}
foreach(string fn in exFileNames){
Regex regEx = new Regex(@"^" + fn.Replace(".",@"\."));
if(regEx.IsMatch(entryName)) include = false;
}
if(include){
s.Add(filename, entryName);
}
counter++;
}
//commit the update once we are done
s.CommitUpdate();
//close the file
s.Close();
}
}
catch(Exception ex)
{
Debug.Log("Exception during processing" + ex.Message);
// No need to rethrow the exception as for our purposes its handled.
}
}
示例3: Metro_EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent
public void Metro_EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent()
{
var data = new byte[] { 1, 2, 3, 4 };
using (var stream = new MemoryStream())
{
using (var zip = new ZipFile())
{
zip.AddEntry(STR_TestBin, data);
zip.Save(stream);
}
stream.Position = 0;
using(var zip = ZipFile.Read(stream))
{
using(var ms = new MemoryStream())
{
zip[STR_TestBin].Extract(ms);
var actual = ms.ToArray();
CollectionAssert.AreEquivalent(data, actual);
}
}
}
}
示例4: Zip
public static void Zip(string zipFileName, params string[] files)
{
#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
string path = Path.GetDirectoryName(zipFileName);
Directory.CreateDirectory(path);
using (ZipFile zip = new ZipFile())
{
foreach (string file in files)
{
zip.AddFile(file, "");
}
zip.Save(zipFileName);
}
#elif UNITY_ANDROID
using (AndroidJavaClass zipper = new AndroidJavaClass ("com.tsw.zipper")) {
{
zipper.CallStatic ("zip", zipFileName, files);
}
}
#elif UNITY_IPHONE
foreach (string file in files) {
addZipFile (file);
}
zip (zipFileName);
#endif
}
示例5: ListZipFile
static void ListZipFile(string fileName, string fileFilter, string directoryFilter)
{
using (ZipFile zipFile = new ZipFile(fileName)) {
var localFileFilter = new PathFilter(fileFilter);
var localDirFilter = new PathFilter(directoryFilter);
if (zipFile.Count == 0) {
Console.WriteLine("No entries to list");
} else {
for (int i = 0; i < zipFile.Count; ++i) {
ZipEntry e = zipFile[i];
if (e.IsFile) {
string path = Path.GetDirectoryName(e.Name);
if (localDirFilter.IsMatch(path)) {
if (localFileFilter.IsMatch(Path.GetFileName(e.Name))) {
Console.WriteLine(e.Name);
}
}
} else if (e.IsDirectory) {
if (localDirFilter.IsMatch(e.Name)) {
Console.WriteLine(e.Name);
}
} else {
Console.WriteLine(e.Name);
}
}
}
}
}
示例6: Main
static public void Main(string[] args)
{
if ( args.Length < 1 ) {
Console.WriteLine("Usage: ZipList file");
return;
}
if ( !File.Exists(args[0]) ) {
Console.WriteLine("Cannot find file");
return;
}
using (ZipFile zFile = new ZipFile(args[0])) {
Console.WriteLine("Listing of : " + zFile.Name);
Console.WriteLine("");
Console.WriteLine("Raw Size Size Date Time Name");
Console.WriteLine("-------- -------- -------- ------ ---------");
foreach (ZipEntry e in zFile) {
DateTime d = e.DateTime;
Console.WriteLine("{0, -10}{1, -10}{2} {3} {4}", e.Size, e.CompressedSize,
d.ToString("dd-MM-yy"), d.ToString("HH:mm"),
e.Name);
}
}
}
示例7: EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent
public void EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent()
{
var data = new byte[] { 1, 2, 3, 4 };
using (var stream = new MemoryStream())
{
using (var zip = new ZipFile())
{
zip.AddEntry(STR_TestBin, data);
zip.Save(stream);
stream.Position = 0;
using (var fs = new FileStream(@"C:\Users\Ivan.z\Documents\test.bin.zip", FileMode.OpenOrCreate))
{
fs.Position = 0;
stream.WriteTo(fs);
}
}
stream.Position = 0;
using (var zip = ZipFile.Read(stream))
{
using (var ms = new MemoryStream())
{
zip[STR_TestBin].Extract(ms);
var actual = ms.ToArray();
CollectionAssert.AreEquivalent(data, actual);
}
}
}
}
示例8: GetFileFromZip
private Action<Stream> GetFileFromZip(string zipPath, string docPath)
{
var fileStream = new FileStream(zipPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var zipFile = new ZipFile(fileStream);
var zipEntry = zipFile.GetEntry(docPath);
if (zipEntry == null || zipEntry.IsFile == false)
return null;
var data = zipFile.GetInputStream(zipEntry);
if (data == null) return null;
return stream =>
{
try
{
if (_disableRequestCompression == false)
stream = new GZipStream(stream, CompressionMode.Compress, leaveOpen: true);
data.CopyTo(stream);
stream.Flush();
}
finally
{
if (_disableRequestCompression == false)
stream.Dispose();
}
};
}
示例9: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = cm.getdt("SELECT * FROM VW_RFI_ATCH_DTL_ALL_ZIP WHERE RAD_RFH_ID = 97");
string output = "<style> table { min-width:600px; padding: 0px; box-shadow: 2px 2px 3px #888888; border: 1px solid #cccccc; -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; border-bottom-left-radius: 0px; -moz-border-radius-bottomright: 0px; -webkit-border-bottom-right-radius: 0px; border-bottom-right-radius: 0px; -moz-border-radius-topright: 0px; -webkit-border-top-right-radius: 0px; border-top-right-radius: 0px; -moz-border-radius-topleft: 0px; -webkit-border-top-left-radius: 0px; border-top-left-radius: 0px; } table table { height: 100%; margin: 0px; padding: 0px; } table tr:last-child td:last-child { -moz-border-radius-bottomright: 0px; -webkit-border-bottom-right-radius: 0px; border-bottom-right-radius: 0px; } table table tr:first-child td:first-child { -moz-border-radius-topleft: 0px; -webkit-border-top-left-radius: 0px; border-top-left-radius: 0px; } table table tr:first-child td:last-child { -moz-border-radius-topright: 0px; -webkit-border-top-right-radius: 0px; border-top-right-radius: 0px; } table tr:last-child td:first-child { -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; border-bottom-left-radius: 0px; } table tr:hover td { background-color: #e5e5e5; } table td { vertical-align: middle; background: -o-linear-gradient(bottom, #ffffff 5%, #e5e5e5 100%); background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffffff), color-stop(1, #e5e5e5) ); background: -moz-linear-gradient( center top, #ffffff 5%, #e5e5e5 100% ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e5e5e5'); background: -o-linear-gradient(top,#ffffff,e5e5e5); background-color: #ffffff; border: 1px solid #cccccc; border-width: 0px 1px 1px 0px; text-align: left; padding: 7px 4px 7px 4px; font-size: 10px; font-family: Arial; font-weight: normal; color: #000000; } table tr:last-child td { border-width: 0px 1px 0px 0px; } table tr td:last-child { border-width: 0px 0px 1px 0px; } table tr:last-child td:last-child { border-width: 0px 0px 0px 0px; } table tr:first-child td { background: -o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) ); background: -moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#b2b2b2'); background: -o-linear-gradient(top,#cccccc,b2b2b2); background-color: #cccccc; border: 0px solid #cccccc; text-align: center; border-width: 0px 0px 1px 1px; font-size: 12px; font-family: Arial; font-weight: bold; color: #000000; } table tr:first-child:hover td { background: -o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) ); background: -moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#b2b2b2'); background: -o-linear-gradient(top,#cccccc,b2b2b2); background-color: #cccccc; } table tr:first-child td:first-child { border-width: 0px 0px 1px 0px; } table tr:first-child td:last-child { border-width: 0px 0px 1px 1px; } table th { background: -o-linear-gradient(bottom, #ffffff 5%, #e5e5e5 100%); background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffffff), color-stop(1, #e5e5e5) ); background: -moz-linear-gradient( center top, #ffffff 5%, #e5e5e5 100% ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e5e5e5'); background: -o-linear-gradient(top,#ffffff,e5e5e5); background-color: #ffffff; border: 1px solid #888888; padding: 3px; font-family: Arial; font-size: 12px; } body { font-family: Arial; font-size: 12px; } </style>";
output += "<div style=''><b>RFI for " + dt.Rows[0]["RAD_RFH_RFINO"].ToString() + "</b></div>";
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.Never;
output += "<table>";
output += "<tr><th>RFI Attach Type</th><th>Insepection</th><th>Remark</th><th>Date</th></tr>";
foreach (DataRow row in dt.Rows)
{
output += "<tr>";
if (File.Exists(Server.MapPath(row["RAD_FILE_SRVR"].ToString())))
{
zip.AddFile(Server.MapPath(row["RAD_FILE_SRVR"].ToString()), (row["file_path"].ToString()));
output += "<td>";
output += (row["RAD_FILE_SRVR_link"].ToString());
output += "</td>";
output += "<td>";
output += (row["RAD_VAL_TYPE"].ToString());
output += "</td>";
output += "<td>";
output += (row["RAD_REMARKS"].ToString());
output += "</td>";
output += "<td>";
output += (row["RAD_DOC_DT"].ToString());
output += "</td>";
}
else
{
output += "<td>";
output += "No file found";
output += "</td>";
output += "<td>";
output += (row["RAD_VAL_TYPE"].ToString());
output += "</td>";
output += "<td>";
output += (row["RAD_REMARKS"].ToString());
output += "</td>";
output += "<td>";
output += (row["RAD_DOC_DT"].ToString());
output += "</td>";
//zip.AddFile("");
}
output += "</tr>";
}
output += "</table>";
byte[] data = Encoding.UTF8.GetBytes(output);
zip.AddEntry("info.html", data);
Response.Clear();
Response.BufferOutput = false;
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=Zip_" + DateTime.Now.ToString("yyyy-MMM-dd-HHmmss") + ".zip");
zip.Save(Response.OutputStream);
Response.End();
}
}
示例10: Before_all_tests
protected override void Before_all_tests()
{
base.Before_all_tests();
_xapPath = Path.GetTempFileName() + ".zip";
_filesToCleanup.Add(_xapPath);
Action<ZipFile> addTempFileToZip = (zipFile) =>
{
var pathToTempFileToPlaceInXap = Path.GetTempFileName();
using (var writer = File.CreateText(pathToTempFileToPlaceInXap))
{
writer.Close();
}
zipFile.AddFile(pathToTempFileToPlaceInXap);
_filesToCleanup.Add(pathToTempFileToPlaceInXap);
};
using (var zipFile = new ZipFile(_xapPath))
{
addTempFileToZip(zipFile);
addTempFileToZip(zipFile);
addTempFileToZip(zipFile);
addTempFileToZip(zipFile);
zipFile.Save();
}
_testFileCollection = new XapReader(new ConsoleLogger(LogChatterLevels.Full)).LoadXapUnderTest(_xapPath);
}
示例11: ExportButton_Click
private void ExportButton_Click(object sender, EventArgs e)
{
this.ExportButton.Enabled = false;
Task.Factory.StartNew(() => {
var exportPath = Path.Combine(Properties.Settings.Default.RomExportPath,
_gameData.GameName + ".zip");
using (var zf = new ZipFile(exportPath))
{
for (int i = 0; i < _gameData.FileNames.Count; i++)
{
var qr = _dataEngine.Query(_gameData.FileNames[i], _gameData.Crc32s[i]).FirstOrDefault();
if (qr != null)
{
var data = GetZipFileByName(_gameData.FileNames[i], qr.ContainerPath);
zf.AddEntry(_gameData.FileNames[i], data);
}
}
zf.Save();
}
Invoke(new Action(() => {
this.ExportButton.Enabled = true;
}));
});
}
示例12: Download
//---------------------------------------------------------------------------------------------------
//--Загрузка книги-----------------------------------------------------------------------------------
public ActionResult Download(Int32 id)
{
UnPack(id); //--распаковываем книгу--
string dirZ = dir.Replace("FanFiction", "TempHtml");
//--Добавляем книгу в .zip архив--
using (ZipFile zip = new ZipFile())
{
zip.TempFileFolder = dir;
zip.AddFile(dirZ + id.ToString() + ".html","");
zip.Save(dirZ + id.ToString() + ".zip");
}
//--Читаем в поток .zip файл--
FileStream fin = new FileStream(dirZ + id.ToString() + ".zip", FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader cin = new StreamReader(fin, System.Text.Encoding.Default);
string stringStream = cin.ReadToEnd();
//--Закрываем соединения и удаляем ненужные файлы--
cin.Close(); fin.Close();
System.IO.File.Delete(dirZ + id.ToString() + ".zip");
System.IO.File.Delete(dirZ + id.ToString() + ".html");
return File(new MemoryStream(System.Text.Encoding.Default.GetBytes(stringStream)), "application/zip", id.ToString() + ".zip");
}
示例13: Compress
//здесь создаем архив
public static void Compress(string directory)
{
if (File.Exists(directory + ".zip"))
File.Delete(directory + ".zip");
ZipFile zf = new ZipFile(directory + ".zip"); //создаем объект - файл архива
zf.AddDirectory(directory); //добавляем туда нашу папку с файлами
zf.Save(); //сохраняем архив
}
示例14: AddManifest
private void AddManifest(ZipFile archive)
{
byte[] manifestBytes = File.ReadAllBytes(packagePath + @"\source.extension.vsixmanifest");
manifestBytes = UpdateManifest(manifestBytes);
archive.AddEntry("extension.vsixmanifest", manifestBytes);
}
示例15: ArchiveManager
/// <include file='Documents/ArchiveManager.xml' path='ArchiveManager/Member[@name="ArchiveManager1"]/*' />
public ArchiveManager(IServiceProvider serviceProvider, string archive)
: base(serviceProvider) {
if (archive != null) {
this.archive = ZipFile.Read(archive);
archivePath = archive;
useArchive = true;
}
}