本文整理汇总了C#中ZipEntry类的典型用法代码示例。如果您正苦于以下问题:C# ZipEntry类的具体用法?C# ZipEntry怎么用?C# ZipEntry使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ZipEntry类属于命名空间,在下文中一共展示了ZipEntry类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: zip
private void zip(string strFile, ZipOutputStream s, string staticFile)
{
if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) strFile += Path.DirectorySeparatorChar;
Crc32 crc = new Crc32();
string[] filenames = Directory.GetFileSystemEntries(strFile);
foreach (string file in filenames)
{
if (Directory.Exists(file))
{
zip(file, s, staticFile);
}
else // 否则直接压缩文件
{
//打开压缩文件
FileStream fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1);
ZipEntry entry = new ZipEntry(tempfile);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
}
}
示例2: Compress
public static void Compress(string path, ZipOutputStream output, string relativePath)
{
if (!string.IsNullOrEmpty(relativePath) && !relativePath.EndsWith("\\"))
{
relativePath += "\\";
}
if (Directory.Exists(path))
{
FileSystemInfo[] fsis = new DirectoryInfo(path).GetFileSystemInfos();
ZipEntry entry = new ZipEntry(relativePath + Path.GetFileName(path) + "/");
entry.DateTime = DateTime.Now;
output.PutNextEntry(entry);
foreach (FileSystemInfo fsi in fsis)
{
Compress(path + "\\" + fsi.Name, output, relativePath + Path.GetFileName(path));
}
}
else
{
Crc32 crc = new Crc32();
//打开压缩文件
Stream fs = File.Open(path, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(relativePath + Path.GetFileName(path));
entry.DateTime = DateTime.Now;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
output.PutNextEntry(entry);
output.Write(buffer, 0, buffer.Length);
}
}
示例3: ZipFiles
public static void ZipFiles(string inputFolderPath, string outPath, string password)
{
ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
// find number of chars to remove // from orginal file path
TrimLength += 1; //remove '\'
FileStream ostream;
byte[] obuffer;
ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream
if (password != null && password != String.Empty)
oZipStream.Password = password;
oZipStream.SetLevel(9); // maximum compression
ZipEntry oZipEntry;
foreach (string Fil in ar) // for each file, generate a zipentry
{
oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
oZipStream.PutNextEntry(oZipEntry);
if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory
{
ostream = File.OpenRead(Fil);
obuffer = new byte[ostream.Length];
ostream.Read(obuffer, 0, obuffer.Length);
oZipStream.Write(obuffer, 0, obuffer.Length);
ostream.Close();
}
}
oZipStream.Finish();
oZipStream.Close();
}
示例4: ZipFile
/// <summary>
/// 压缩单个文件
/// </summary>
/// <param name="fileToZip">要进行压缩的文件名</param>
/// <param name="zipedFile">压缩后生成的压缩文件名</param>
/// <param name="level">压缩等级</param>
/// <param name="password">密码</param>
/// <param name="onFinished">压缩完成后的代理</param>
public static void ZipFile(string fileToZip, string zipedFile, string password = "", int level = 5, OnFinished onFinished = null)
{
//如果文件没有找到,则报错
if (!File.Exists(fileToZip))
throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
using (FileStream fs = File.OpenRead(fileToZip))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
using (FileStream ZipFile = File.Create(zipedFile))
{
using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
{
string fileName = fileToZip.Substring(fileToZip.LastIndexOf("/") + 1);
ZipEntry ZipEntry = new ZipEntry(fileName);
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(level);
ZipStream.Password = password;
ZipStream.Write(buffer, 0, buffer.Length);
ZipStream.Finish();
ZipStream.Close();
if (null != onFinished) onFinished();
}
}
}
}
示例5: Compression
private static byte[] Compression(byte[] bytes)
{
MemoryStream ms = new MemoryStream();
ZipOutputStream zos = new ZipOutputStream(ms);
ZipEntry ze = new ZipEntry(ConfigConst.ZipEntryName);
zos.PutNextEntry(ze);
zos.SetLevel(9);
zos.Write(bytes, 0, bytes.Length);//写入压缩文件
zos.Close();
return ms.ToArray();
}
示例6: WriteZipFile
public static void WriteZipFile(List<FileDetails> filesToZip, string path,string manifestPath,string manifest )
{
int compression = 9;
FileDetails fd = new FileDetails(manifest, manifestPath,manifestPath);
filesToZip.Insert(0,fd);
foreach (FileDetails obj in filesToZip)
if (!File.Exists(obj.FilePath))
throw new ArgumentException(string.Format("The File {0} does not exist!", obj.FileName));
Object _locker=new Object();
lock(_locker)
{
Crc32 crc32 = new Crc32();
ZipOutputStream stream = new ZipOutputStream(File.Create(path));
stream.SetLevel(compression);
for (int i = 0; i < filesToZip.Count; i++)
{
ZipEntry entry = new ZipEntry(filesToZip[i].FolderInfo + "/" + filesToZip[i].FileName);
entry.DateTime = DateTime.Now;
if (i == 0)
{
entry = new ZipEntry(manifest);
}
using (FileStream fs = File.OpenRead(filesToZip[i].FilePath))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
entry.Size = fs.Length;
fs.Close();
crc32.Reset();
crc32.Update(buffer);
entry.Crc = crc32.Value;
stream.PutNextEntry(entry);
stream.Write(buffer, 0, buffer.Length);
}
}
stream.Finish();
stream.Close();
DeleteManifest(manifestPath);
}
}
示例7: Evaluate
internal override bool Evaluate(ZipEntry entry)
{
bool result = Left.Evaluate(entry);
switch (Conjunction)
{
case LogicalConjunction.AND:
if (result)
result = Right.Evaluate(entry);
break;
case LogicalConjunction.OR:
if (!result)
result = Right.Evaluate(entry);
break;
case LogicalConjunction.XOR:
result ^= Right.Evaluate(entry);
break;
}
return result;
}
示例8: Main
public static void Main(string[] args)
{
string[] filenames = Directory.GetFiles(args[0]);
Crc32 crc = new Crc32();
ZipOutputStream s = new ZipOutputStream(File.Create(args[1]));
s.SetLevel(6); // 0 - store only to 9 - means best compression
foreach (string file in filenames) {
FileStream fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(file);
entry.DateTime = DateTime.Now;
// set Size and the crc, because the information
// about the size and crc should be stored in the header
// if it is not set it is automatically written in the footer.
// (in this case size == crc == -1 in the header)
// Some ZIP programs have problems with zip files that don't store
// the size and crc in the header.
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
s.Finish();
s.Close();
}
示例9: ZipData
/// <summary>
/// Архивирует данные одного потока в другой поток.
/// </summary>
/// <param name="inputStream">Входной поток.</param>
/// <param name="outputStream">Выходной поток.</param>
/// <param name="entryFileName">Имя файла, которое будет помещено в выходном архиве.</param>
public static void ZipData( Stream inputStream, Stream outputStream, string entryFileName )
{
Crc32 crc = new Crc32();
ZipOutputStream zipStream = new ZipOutputStream( outputStream );
// начинаем архивировать
zipStream.SetLevel( 9 ); // уровень сжатия
long length = inputStream.Length;
byte[] buffer = new byte[length];
inputStream.Read( buffer, 0, buffer.Length );
ZipEntry entry = new ZipEntry( entryFileName );
entry.DateTime = DateTime.Now;
entry.Size = length;
crc.Reset();
crc.Update( buffer );
entry.Crc = crc.Value;
zipStream.PutNextEntry( entry );
zipStream.Write( buffer, 0, buffer.Length );
zipStream.Finish();
}
示例10: ExtractEmbeddedZipFile
/// <summary>
/// Process a ZIP file that is embedded within the parent ZIP file. Its contents are extracted and turned into
/// albums and media objects just like items in the parent ZIP file.
/// </summary>
/// <param name="zipFile">A reference to a ZIP file contained within the parent ZIP file. Notice that we don't do
/// anything with this parameter other than verify that its extension is "ZIP". That's because we actually extract
/// the file from the parent ZIP file by calling the ExtractMediaObjectFile method, which extracts the file from
/// the class-level member variable _zipStream</param>
/// <param name="parentAlbum">The album that should contain the top-level directories and files found in the ZIP
/// file.</param>
private void ExtractEmbeddedZipFile(ZipEntry zipFile, IAlbum parentAlbum)
{
#region Validation
if (Path.GetExtension(zipFile.Name).ToUpperInvariant() != ".ZIP")
{
throw new ArgumentException(String.Concat("The zipFile parameter of the method ExtractEmbeddedZipFile in class ZipUtility must be a ZIP file. Instead, it had the file extension ", Path.GetExtension(zipFile.Name), "."));
}
if (parentAlbum == null)
{
throw new ArgumentNullException("parentAlbum");
}
#endregion
string filepath = Path.Combine(parentAlbum.FullPhysicalPathOnDisk, Guid.NewGuid().ToString("N") + ".config");
try
{
ExtractMediaObjectFile(filepath);
using (ZipUtility zip = new ZipUtility(this._userName, this._roles))
{
this._skippedFiles.AddRange(zip.ExtractZipFile(new FileInfo(filepath).OpenRead(), parentAlbum, true));
}
}
finally
{
File.Delete(filepath);
}
}
示例11: AddMediaObjectToGallery
/// <summary>
/// Adds the <paramref name="zipContentFile"/> as a media object to the <paramref name="album"/>.
/// </summary>
/// <param name="zipContentFile">A reference to a file in a ZIP archive.</param>
/// <param name="album">The album to which the file should be added as a media object.</param>
private void AddMediaObjectToGallery(ZipEntry zipContentFile, IAlbum album)
{
string zipFileName = Path.GetFileName(zipContentFile.Name).Trim();
if (zipFileName.Length == 0)
return;
string uniqueFilename = HelperFunctions.ValidateFileName(album.FullPhysicalPathOnDisk, zipFileName);
string uniqueFilepath = Path.Combine(album.FullPhysicalPathOnDisk, uniqueFilename);
// Extract the file from the zip stream and save as the specified filename.
ExtractMediaObjectFile(uniqueFilepath);
// Get the file we just saved to disk.
FileInfo mediaObjectFile = new FileInfo(uniqueFilepath);
try
{
IGalleryObject mediaObject = Factory.CreateMediaObjectInstance(mediaObjectFile, album);
HelperFunctions.UpdateAuditFields(mediaObject, this._userName);
mediaObject.Save();
if ((_discardOriginalImage) && (mediaObject is Business.Image))
{
((Business.Image)mediaObject).DeleteHiResImage();
mediaObject.Save();
}
}
catch (ErrorHandler.CustomExceptions.UnsupportedMediaObjectTypeException ex)
{
this._skippedFiles.Add(new KeyValuePair<string, string>(mediaObjectFile.Name, ex.Message));
File.Delete(mediaObjectFile.FullName);
}
}
示例12: VerifyAlbumExistsAndReturnReference
private IAlbum VerifyAlbumExistsAndReturnReference(ZipEntry zipContentFile, IAlbum rootParentAlbum)
{
// Get the directory path of the next file or directory within the zip file.
// Ex: album1\album2\album3, album1
string zipDirectoryPath = Path.GetDirectoryName(zipContentFile.Name);
string[] directoryNames = zipDirectoryPath.Split(new char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
string albumFullPhysicalPath = rootParentAlbum.FullPhysicalPathOnDisk;
IAlbum currentAlbum = rootParentAlbum;
foreach (string directoryNameFromZip in directoryNames)
{
string shortenedDirName = GetPreviouslyCreatedTruncatedAlbumName(albumFullPhysicalPath, directoryNameFromZip);
// Ex: c:\inetpub\wwwroot\galleryserver\mypics\2006\album1
albumFullPhysicalPath = System.IO.Path.Combine(albumFullPhysicalPath, shortenedDirName);
IAlbum newAlbum = null;
if (Directory.Exists(albumFullPhysicalPath))
{
// Directory exists, so there is probably an album corresponding to it. Find it.
IGalleryObjectCollection childGalleryObjects = currentAlbum.GetChildGalleryObjects(GalleryObjectType.Album);
foreach (IGalleryObject childGalleryObject in childGalleryObjects)
{
if (childGalleryObject.FullPhysicalPathOnDisk == albumFullPhysicalPath)
{
newAlbum = childGalleryObject as Album; break;
}
}
if (newAlbum == null)
{
// No album in the database matches that directory. Add it.
// Before we add the album, we need to make sure the user has permission to add the album. Check if user
// is authenticated and if the current album is the one passed into this method. It can be assumed that any
// other album we encounter has been created by this method and we checked for permission when it was created.
if (this._isAuthenticated && (currentAlbum.Id == rootParentAlbum.Id))
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.AddChildAlbum, this._roles, currentAlbum.Id, this._isAuthenticated, currentAlbum.IsPrivate);
newAlbum = Factory.CreateAlbumInstance();
newAlbum.Parent = currentAlbum;
newAlbum.IsPrivate = currentAlbum.IsPrivate;
newAlbum.DirectoryName = directoryNameFromZip;
HelperFunctions.UpdateAuditFields(newAlbum, this._userName);
newAlbum.Save();
}
}
else
{
// The directory doesn't exist. Create an album.
// Before we add the album, we need to make sure the user has permission to add the album. Check if user
// is authenticated and if the current album is the one passed into this method. It can be assumed that any
// other album we encounter has been created by this method and we checked for permission when it was created.
if (this._isAuthenticated && (currentAlbum.Id == rootParentAlbum.Id))
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.AddChildAlbum, this._roles, currentAlbum.Id, this._isAuthenticated, currentAlbum.IsPrivate);
newAlbum = Factory.CreateAlbumInstance();
newAlbum.IsPrivate = currentAlbum.IsPrivate;
newAlbum.Parent = currentAlbum;
newAlbum.Title = directoryNameFromZip;
HelperFunctions.UpdateAuditFields(newAlbum, this._userName);
newAlbum.Save();
// If the directory name written to disk is different than the name from the zip file, add it to
// our hash table.
if (!directoryNameFromZip.Equals(newAlbum.DirectoryName))
{
this._albumAndDirectoryNamesLookupTable.Add(Path.Combine(currentAlbum.FullPhysicalPathOnDisk, directoryNameFromZip), Path.Combine(currentAlbum.FullPhysicalPathOnDisk, newAlbum.DirectoryName));
}
}
currentAlbum = newAlbum;
}
return currentAlbum;
}
示例13: InitializeAESPassword
/// <summary>
/// Initializes encryption keys based on given password.
/// </summary>
protected void InitializeAESPassword(ZipEntry entry, string rawPassword,
out byte[] salt, out byte[] pwdVerifier) {
salt = new byte[entry.AESSaltLen];
// Salt needs to be cryptographically random, and unique per file
if (_aesRnd == null)
_aesRnd = new RNGCryptoServiceProvider();
_aesRnd.GetBytes(salt);
int blockSize = entry.AESKeySize / 8; // bits to bytes
cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true);
pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier;
}
示例14: lBtnDownloadAlbum_Click
//.........这里部分代码省略.........
objListPhotos = objMisc.GetPhotoImagesList(objPhotos);
if ((DownloadPhotoAlbumId > 0) && (objListPhotos.Count > 0))
{
// zip up the files
try
{
string sTargetFolderPath = getPath[0] + "/" + getPath[1] + "/" + _tributeUrl.Replace(" ", "_") + "_" + _tributeType.Replace(" ", "_");
//to create directory for image.
string galleryPath = getPath[0] + "/" + getPath[1] + "/" + getPath[6];
string sZipFileName = "Album_" + DownloadPhotoAlbumId.ToString();
string[] filenames = Directory.GetFiles(sTargetFolderPath);
// Zip up the files - From SharpZipLib Demo Code
using (ZipOutputStream s = new ZipOutputStream(File.Create(galleryPath + "\\" + sZipFileName + ".zip")))
{
s.SetLevel(9); // 0-9, 9 being the highest level of compression
byte[] buffer = new byte[4096];
foreach (Photos objPhoto in objListPhotos)
{
bool Foundflag = true;
string ImageFile = string.Empty;
string smallFile = string.Empty;
ImageFile = sTargetFolderPath + "\\" + "/Big_" + objPhoto.PhotoImage;
smallFile = sTargetFolderPath + "\\" + objPhoto.PhotoImage;
foreach (string file in filenames)
{
if ((file.EndsWith("Big_" + objPhoto.PhotoImage)) && (File.Exists(ImageFile)))
{
Foundflag = false; //FlagsAttribute set false for small image
//Code to zip
ZipEntry entry = new ZipEntry(Path.GetFileName(ImageFile));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(ImageFile))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
//Code to zip till here
}
}
if (Foundflag) // if big image is not found.
{
foreach (string file in filenames)
{
if ((file.EndsWith(objPhoto.PhotoImage)) && (File.Exists(smallFile)) && (!(file.EndsWith("Big_" + objPhoto.PhotoImage))))
//(File.Exists(smallFile))
{
ZipEntry entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
示例15: ZipAndroidResources
public static void ZipAndroidResources()
{
try
{
var filenames = GatherAndroidResourceFiles();
// '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 zipStream = new ZipOutputStream(File.Create(Application.dataPath + "/Android.zip")))
{
zipStream.SetLevel(9); // 0 - store only to 9 - means best compression
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
string name = file.Substring(AndroidResourceFolder.Length + 1);
ZipEntry entry = new ZipEntry(name);
// Setup the entry data as required.
// Crc and size are handled by the library for seakable streams
// so no need to do them here.
// Could also use the last write time or similar for the file.
entry.DateTime = System.DateTime.Now;
zipStream.PutNextEntry(entry);
using (FileStream fileStream = File.OpenRead(file))
{
// Using a fixed size buffer here makes no noticeable difference for output
// but keeps a lid on memory usage.
int sourceBytes;
do
{
sourceBytes = fileStream.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
// Finish/Close arent needed strictly as the using statement does this automatically
// Finish is important to ensure trailing information for a Zip file is appended. Without this
// the created file would be invalid.
zipStream.Finish();
// Close is important to wrap things up and unlock the file.
zipStream.Close();
AssetDatabase.Refresh();
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("Exception during processing {0}", ex));
// No need to rethrow the exception as for our purposes its handled.
}
}