本文整理汇总了C#中ICSharpCode.SharpZipLib.Zip.ZipFile.Close方法的典型用法代码示例。如果您正苦于以下问题:C# ZipFile.Close方法的具体用法?C# ZipFile.Close怎么用?C# ZipFile.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ICSharpCode.SharpZipLib.Zip.ZipFile
的用法示例。
在下文中一共展示了ZipFile.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Basics
public void Basics()
{
const string tempName1 = "a(1).dat";
MemoryStream target = new MemoryStream();
string tempFilePath = GetTempFilePath();
Assert.IsNotNull(tempFilePath, "No permission to execute this test?");
string addFile = Path.Combine(tempFilePath, tempName1);
MakeTempFile(addFile, 1);
try {
FastZip fastZip = new FastZip();
fastZip.CreateZip(target, tempFilePath, false, @"a\(1\)\.dat", null);
MemoryStream archive = new MemoryStream(target.ToArray());
using (ZipFile zf = new ZipFile(archive)) {
Assert.AreEqual(1, zf.Count);
ZipEntry entry = zf[0];
Assert.AreEqual(tempName1, entry.Name);
Assert.AreEqual(1, entry.Size);
Assert.IsTrue(zf.TestArchive(true));
zf.Close();
}
}
finally {
File.Delete(tempName1);
}
}
示例2: GetFirstZipEntryWithEnding
public static string GetFirstZipEntryWithEnding(string zipfile, string ending)
{
#if SHARPZIPLIB
if (string.IsNullOrEmpty(zipfile))
return null;
ZipFile zf = null;
try
{
zf = new ZipFile(zipfile);
}
catch (Exception)
{
return null;
}
string name = null;
foreach (ZipEntry zipEntry in zf)
{
if (zipEntry.Name.ToLower().EndsWith(ending))
{
name = zipEntry.Name;
break;
}
}
zf.Close();
return name;
#else
return null;
#endif
}
示例3: 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.
}
}
示例4: ExtractZipFile
public static void ExtractZipFile(string archiveFilenameIn, string outFolder,
Func<ZipEntry, String, bool> entryCheckFunc,
string password = null)
{
ZipFile zf = null;
try
{
FileStream fs = File.OpenRead(archiveFilenameIn);
zf = new ZipFile(fs);
if (!String.IsNullOrEmpty(password))
{
zf.Password = password; // AES encrypted entries are handled automatically
}
foreach (ZipEntry zipEntry in zf)
{
if (!zipEntry.IsFile)
{
continue; // Ignore directories
}
String entryFileName = zipEntry.Name;
// to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
// Optionally match entrynames against a selection list here to skip as desired.
// The unpacked length is available in the zipEntry.Size property.
// Manipulate the output filename here as desired.
String fullZipToPath = Path.Combine(outFolder, entryFileName);
string directoryName = Path.GetDirectoryName(fullZipToPath);
if (entryCheckFunc(zipEntry, fullZipToPath)) continue;
if (directoryName.Length > 0)
Directory.CreateDirectory(directoryName);
byte[] buffer = new byte[4096]; // 4K is optimum
Stream zipStream = zf.GetInputStream(zipEntry);
// Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
// of the file, but does not waste memory.
// The "using" will close the stream even if an exception occurs.
using (FileStream streamWriter = File.Create(fullZipToPath))
{
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
}
}
catch (Exception ex)
{
throw new Exception("ExtractZipFile failed", ex);
}
finally
{
if (zf != null)
{
zf.IsStreamOwner = true; // Makes close also shut the underlying stream
zf.Close(); // Ensure we release resources
}
}
}
示例5: TestLargeZip
void TestLargeZip(string tempFile, int targetFiles)
{
const int BlockSize = 4096;
byte[] data = new byte[BlockSize];
byte nextValue = 0;
for (int i = 0; i < BlockSize; ++i)
{
nextValue = ScatterValue(nextValue);
data[i] = nextValue;
}
using (ZipFile zFile = new ZipFile(tempFile))
{
Assert.AreEqual(targetFiles, zFile.Count);
byte[] readData = new byte[BlockSize];
int readIndex;
foreach (ZipEntry ze in zFile)
{
Stream s = zFile.GetInputStream(ze);
readIndex = 0;
while (readIndex < readData.Length)
{
readIndex += s.Read(readData, readIndex, data.Length - readIndex);
}
for (int ii = 0; ii < BlockSize; ++ii)
{
Assert.AreEqual(data[ii], readData[ii]);
}
}
zFile.Close();
}
}
示例6: Run
public void Run()
{
try
{
Stream filestream = File.OpenRead(Filename);
// SWC file: extract 'library.swf' file
if (Filename.EndsWith(".swc", StringComparison.OrdinalIgnoreCase))
{
ZipFile zfile = new ZipFile(filestream);
foreach (ZipEntry entry in zfile)
{
if (entry.Name.EndsWith(".swf", StringComparison.OrdinalIgnoreCase))
{
ExploreSWF(new MemoryStream(UnzipFile(zfile, entry)));
}
else if (entry.Name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)
&& entry.Name.StartsWith("docs/"))
{
Docs[entry.Name] = UnzipFile(zfile, entry);
}
else if (entry.Name == "catalog.xml")
{
Catalog = UnzipFile(zfile, entry);
}
}
zfile.Close();
filestream.Close();
}
else
{
byte[] data = new byte[filestream.Length];
filestream.Read(data, 0, (int)filestream.Length);
filestream.Close();
Stream dataStream = new MemoryStream(data);
// raw ABC bytecode
if (Filename.EndsWith(".abc", StringComparison.OrdinalIgnoreCase))
{
BinaryReader br = new BinaryReader(dataStream);
Abc abc = new Abc(br);
ExploreABC(abc);
}
// regular SWF
else if (Filename.EndsWith(".swf", StringComparison.OrdinalIgnoreCase))
{
ExploreSWF(dataStream);
}
else Errors.Add("Error: Not a supported filetype");
}
}
catch (FileNotFoundException)
{
Errors.Add("Error: File not found");
}
catch (Exception ex)
{
Errors.Add("Error: " + ex.Message);
}
}
示例7: AddToZip
/// <summary>
/// Add files to an existing Zip archive,
/// </summary>
/// <param name="filename">Array of path / filenames to add to the archive</param>
/// <param name="archive">Zip archive that we want to add the file to</param>
public void AddToZip(string[] filename, string archive)
{
if (!File.Exists(archive))
{
return;
}
try
{
ZipFile zf = new ZipFile(archive);
zf.BeginUpdate();
// path relative to the archive
zf.NameTransform = new ZipNameTransform(Path.GetDirectoryName(archive));
foreach (var file in filename)
{
// skip if this isn't a real file
if (!File.Exists(file))
{
continue;
}
zf.Add(file, CompressionMethod.Deflated);
}
zf.CommitUpdate();
zf.Close();
}
catch (Exception e)
{
if (e.Message != null)
{
var msg = new[] { e.Message };
LocDB.Message("defErrMsg", e.Message, msg, LocDB.MessageTypes.Error, LocDB.MessageDefault.First);
}
}
}
示例8: ExtractResourceZip
/// <summary>
/// extract file from zipped resource, and place to temp folder
/// </summary>
/// <param name="resource">resource name</param>
/// <param name="fileName">output name</param>
/// <param name="OverWriteIfExists">if true,will overwrite the file even if the file exists</param>
private void ExtractResourceZip(byte[] resource, string fileName, bool OverWriteIfExists = false, int BufferSize = BUFFERSIZE)
{
string target = WorkingPath + fileName;
if (OverWriteIfExists || !File.Exists(target))
{
ZipFile zip = null;
FileStream fs = null;
Stream inStream = null;
try
{
zip = new ZipFile(new MemoryStream(resource));
inStream = zip.GetInputStream(zip.GetEntry(fileName));
fs = new FileStream(target, FileMode.Create);
byte[] buff = new byte[BufferSize];
int read_count;
while ((read_count = inStream.Read(buff, 0, BufferSize)) > 0)
{
fs.Write(buff, 0, read_count);
}
}
catch { }
finally
{
if (zip != null) zip.Close();
if (fs != null) fs.Close();
if (inStream != null) inStream.Close();
}
}
}
示例9: install
public bool install(string target)
{
if (!File.Exists(target))
{
return false;
}
ZipFile zip = new ZipFile(target);
bool neednewgamedirectory = true;
try
{
foreach (ZipEntry item in zip)
{
if (item.Name.StartsWith(MeCore.Config.Server.ClientPath ?? ".minecraft"))
{
neednewgamedirectory = false;
continue;
}
if (!item.IsFile)
{
continue;
}
string entryFileName = item.Name;
byte[] buffer = new byte[4096];
Stream zipStream = zip.GetInputStream(item);
string fullZipToPath = "";
if (neednewgamedirectory)
{
fullZipToPath = Path.Combine(MeCore.BaseDirectory, MeCore.Config.Server.ClientPath ?? ".minecraft", entryFileName);
}
else
{
fullZipToPath = Path.Combine(MeCore.BaseDirectory, entryFileName);
}
string directoryName = Path.GetDirectoryName(fullZipToPath);
if (directoryName.Length > 0)
Directory.CreateDirectory(directoryName);
using (FileStream streamWriter = File.Create(fullZipToPath))
{
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
}
}
catch (Exception ex)
{
MeCore.Invoke(new Action(() => MeCore.MainWindow.addNotice(new Notice.CrashErrorBar(string.Format(LangManager.GetLangFromResource("ErrorNameFormat"), DateTime.Now.ToLongTimeString()), ex.ToWellKnownExceptionString()) { ImgSrc = new BitmapImage(new Uri("pack://application:,,,/Resources/error-banner.jpg")) })));
}
finally
{
if (zip != null)
{
zip.IsStreamOwner = true;
zip.Close();
}
}
return true;
}
示例10: GetAndUnpackLatestVersion
public void GetAndUnpackLatestVersion()
{
var client = new WebClient();
string usersTempFolder = Path.GetTempPath();
string updateZipName = string.Format("v{0}.zip", _newVersion);
string updateZipLocation = Path.Combine(usersTempFolder, updateZipName);
client.DownloadFile(Path.Combine(ConfigurationManager.AppSettings["updatePackageAddress"], updateZipName),
updateZipLocation);
string updatePackageFullPath = Path.Combine(usersTempFolder, _newVersion.ToString());
ZipFile zf = null;
try
{
FileStream fs = File.OpenRead(updateZipLocation);
zf = new ZipFile(fs);
foreach (ZipEntry zipEntry in zf)
{
if (!zipEntry.IsFile)
{
continue;
}
String entryFileName = zipEntry.Name;
var buffer = new byte[4096];
Stream zipStream = zf.GetInputStream(zipEntry);
String fullZipToPath = Path.Combine(updatePackageFullPath, Path.GetFileName(entryFileName));
string directoryName = Path.GetDirectoryName(fullZipToPath);
if (directoryName.Length > 0)
{
Directory.CreateDirectory(directoryName);
}
using (FileStream streamWriter = File.Create(fullZipToPath))
{
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
}
}
finally
{
if (zf != null)
{
zf.IsStreamOwner = true;
zf.Close();
}
}
_updatePackageFullPath = updatePackageFullPath;
}
示例11: RunWholeProcedure
public static void RunWholeProcedure()
{
Compile.currentMooegeExePath = Program.programPath + @"\" + @"Repositories\" + ParseRevision.developerName + "-" + ParseRevision.branchName + "-" + ParseRevision.lastRevision + @"\src\Mooege\bin\Debug\Mooege.exe";
Compile.currentMooegeDebugFolderPath = Program.programPath + @"\" + @"Repositories\" + ParseRevision.developerName + "-" + ParseRevision.branchName + "-" + ParseRevision.lastRevision + @"\src\Mooege\bin\Debug\";
Compile.mooegeINI = Program.programPath + @"\" + @"Repositories\" + ParseRevision.developerName + "-" + ParseRevision.branchName + "-" + ParseRevision.lastRevision + @"\src\Mooege\bin\Debug\config.ini";
ZipFile zip = null;
var events = new FastZipEvents();
if (ProcessFinder.FindProcess("Mooege") == true)
{
ProcessFinder.KillProcess("Mooege");
}
FastZip z = new FastZip(events);
Console.WriteLine("Uncompressing zip file...");
var stream = new FileStream(Program.programPath + @"\Repositories\" + @"\Mooege.zip", FileMode.Open, FileAccess.Read);
zip = new ZipFile(stream);
zip.IsStreamOwner = true; //Closes parent stream when ZipFile.Close is called
zip.Close();
var t1 = Task.Factory.StartNew(() => z.ExtractZip(Program.programPath + @"\Repositories\" + @"\Mooege.zip", Program.programPath + @"\" + @"Repositories\", null))
.ContinueWith(delegate
{
//Comenting the lines below because I haven't tested this new way over XP VM or even normal XP.
//RefreshDesktop.RefreshDesktopPlease(); //Sends a refresh call to desktop, probably this is working for Windows Explorer too, so i'll leave it there for now -wesko
//Thread.Sleep(2000); //<-This and ^this is needed for madcow to work on VM XP, you need to wait for Windows Explorer to refresh folders or compiling wont find the new mooege folder just uncompressed.
Console.WriteLine("Uncompress Complete.");
if (File.Exists(Program.madcowINI))
{
IConfigSource source = new IniConfigSource(Program.madcowINI);
String Src = source.Configs["Balloons"].Get("ShowBalloons");
if (Src.Contains("1"))
{
Form1.GlobalAccess.MadCowTrayIcon.ShowBalloonTip(1000, "MadCow", "Uncompress Complete!", ToolTipIcon.Info);
}
}
Form1.GlobalAccess.Invoke((MethodInvoker)delegate { Form1.GlobalAccess.generalProgressBar.PerformStep(); });
Compile.compileSource(); //Compile solution projects.
Form1.GlobalAccess.Invoke((MethodInvoker)delegate { Form1.GlobalAccess.generalProgressBar.PerformStep(); });
Form1.GlobalAccess.Invoke((MethodInvoker)delegate { Form1.GlobalAccess.generalProgressBar.PerformStep(); });
Console.WriteLine("[Process Complete!]");
if (File.Exists(Program.madcowINI))
{
IConfigSource source = new IniConfigSource(Program.madcowINI);
String Src = source.Configs["Balloons"].Get("ShowBalloons");
if (Src.Contains("1"))
{
Form1.GlobalAccess.MadCowTrayIcon.ShowBalloonTip(1000, "MadCow", "Process Complete!", ToolTipIcon.Info);
}
}
});
}
示例12: Main
public static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("SwfOp <file.swf>: list all library symbols of the SWF");
return;
}
string filename = args[args.Length-1];
operation = (args.Length > 1) ? args[0] : "-list";
// read SWF
try
{
Stream filestream = File.OpenRead(filename);
// SWC file: extract 'library.swf' file
if (filename.EndsWith(".swc", StringComparison.OrdinalIgnoreCase))
{
ZipFile zfile = new ZipFile(filestream);
foreach(ZipEntry entry in zfile)
{
if (entry.Name.EndsWith(".swf", StringComparison.OrdinalIgnoreCase))
{
ExploreSWF(new MemoryStream(UnzipFile(zfile, entry)));
}
else if (entry.Name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)
&& entry.Name.StartsWith("docs/"))
{
string docSrc = Encoding.UTF8.GetString(UnzipFile(zfile, entry));
}
}
zfile.Close();
filestream.Close();
}
else if (filename.EndsWith(".abc", StringComparison.OrdinalIgnoreCase))
{
byte[] data = new byte[filestream.Length];
filestream.Read(data, 0, (int)filestream.Length);
BinaryReader br = new BinaryReader(new MemoryStream(data));
Abc abc = new Abc(br);
}
// regular SWF
else ExploreSWF(new BufferedStream(filestream));
}
catch(FileNotFoundException)
{
Console.WriteLine("-- SwfOp Error: File not found");
}
catch(Exception ex)
{
Console.WriteLine("-- SwfOp Error: "+ex.Message);
}
Console.ReadLine();
}
示例13: Unzip
public IList<string> Unzip(string archiveFile, string destinationDirectory)
{
IList<string> files = new List<string>();
ZipFile zf = null;
try
{
FileStream fs = File.OpenRead(archiveFile);
zf = new ZipFile(fs);
foreach (ZipEntry zipEntry in zf)
{
if (!zipEntry.IsFile)
{
continue;
}
String entryFileName = zipEntry.Name;
// to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
// Optionally match entrynames against a selection list here to skip as desired.
// The unpacked length is available in the zipEntry.Size property.
byte[] buffer = new byte[4096]; // 4K is optimum
Stream zipStream = zf.GetInputStream(zipEntry);
// Manipulate the output filename here as desired.
String fullZipToPath = Path.Combine(destinationDirectory, entryFileName);
string directoryName = Path.GetDirectoryName(fullZipToPath);
if (directoryName.Length > 0)
Directory.CreateDirectory(directoryName);
// Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
// of the file, but does not waste memory.
// The "using" will close the stream even if an exception occurs.
using (FileStream streamWriter = File.Create(fullZipToPath))
{
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
files.Add(fullZipToPath);
}
}
finally
{
if (zf != null)
{
zf.IsStreamOwner = true; // Makes close also shut the underlying stream
zf.Close(); // Ensure we release resources
}
}
return files;
}
示例14: AssertDoesNotContainFile
private void AssertDoesNotContainFile(string partialPath)
{
ZipFile f = null;
try
{
f = new ZipFile(_destinationZip);
Assert.AreEqual(-1, f.FindEntry(GetZipFileInternalPath(partialPath), true));
}
finally
{
if (f != null)
{
f.Close();
}
}
}
示例15: GetContentRaw
public byte[] GetContentRaw(string loc)
{
byte[] cont = null;
ZipFile zipFile = new ZipFile(FileLoc);
int i = zipFile.FindEntry(loc, false);
if (i >= 0)
{
ZipEntry ze = zipFile[i];
Stream s = zipFile.GetInputStream(ze);
byte[] buff = new byte[(int)ze.Size];
s.Read(buff, 0, buff.Length);
cont = buff;
}
zipFile.Close();
return cont;
}