Beispiel #1
2
        /// <summary>
        /// Creates a zip archive from a byte array
        /// </summary>
        /// <param name="buffer">The file in byte[] format</param>
        /// <param name="fileName">The name of the file you want to add to the archive</param>
        /// <returns></returns>
        public static byte[] CreateZipByteArray(byte[] buffer, string fileName)
        {
            ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();

            using (System.IO.MemoryStream zipMemoryStream = new System.IO.MemoryStream())
            {
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(zipMemoryStream);

                zipOutputStream.SetLevel(6);

                ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
                zipEntry.DateTime = DateTime.Now;
                zipEntry.Size = buffer.Length;

                crc.Reset();
                crc.Update(buffer);
                zipEntry.Crc = crc.Value;
                zipOutputStream.PutNextEntry(zipEntry);
                zipOutputStream.Write(buffer, 0, buffer.Length);

                zipOutputStream.Finish();

                byte[] zipByteArray = new byte[zipMemoryStream.Length];
                zipMemoryStream.Position = 0;
                zipMemoryStream.Read(zipByteArray, 0, (int)zipMemoryStream.Length);

                zipOutputStream.Close();

                return zipByteArray;
            }
        }
Beispiel #2
0
        /// <summary>
        /// Create a zip file of the supplied file names and string data source
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully creating the zip file.</returns>
        public static bool ZipData(string zipPath, Dictionary<string, string> filenamesAndData)
        {
            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    stream.SetLevel(0);
                    foreach (var filename in filenamesAndData.Keys)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(filename);
                        var data = filenamesAndData[filename];
                        var bytes = Encoding.Default.GetBytes(data);
                        stream.PutNextEntry(entry);
                        stream.Write(bytes, 0, bytes.Length);
                        stream.CloseEntry();
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error(err);
                return false;
            }
            return true;
        }
 public static void Zip(string data, string zipPath, string zipEntry)
 {
     using (var stream = new ZipOutputStream(File.Create(zipPath)))
     {
         var entry = new ZipEntry(zipEntry);
         stream.PutNextEntry(entry);
         var buffer = new byte[4096];
         using (var dataReader = new MemoryStream(Encoding.Default.GetBytes(data)))
         {
             int sourceBytes;
             do
             {
                 sourceBytes = dataReader.Read(buffer, 0, buffer.Length);
                 stream.Write(buffer, 0, sourceBytes);
             }while (sourceBytes > 0);
         }
     }
 }
Beispiel #4
0
        public static void DownloadZipToBrowser(System.Collections.Generic.List <string> zipFileList)
        {
            System.Web.HttpContext.Current.Response.ContentType = "application/zip";
            // If the browser is receiving a mangled zipfile, IIS Compression may cause this problem. Some members have found that
            //Response.ContentType = "application/octet-stream" has solved this. May be specific to Internet Explorer.

            System.Web.HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename=\"Download.zip\"");
            System.Web.HttpContext.Current.Response.CacheControl = "Private";
            System.Web.HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddMinutes(5)); // or put a timestamp in the filename in the content-disposition

            byte[] buffer = new byte[4096];

            var zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.Web.HttpContext.Current.Response.OutputStream);

            zipOutputStream.SetLevel(3); //0-9, 9 being the highest level of compression

            foreach (string fileName in zipFileList)
            {
                Stream fs    = File.OpenRead(TM.IO.FileDirectory.MapPath(fileName)); // or any suitable inputstream
                var    entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(ICSharpCode.SharpZipLib.Zip.ZipEntry.CleanName(fileName));
                entry.Size = fs.Length;
                // Setting the Size provides WinXP built-in extractor compatibility,
                //  but if not available, you can set zipOutputStream.UseZip64 = UseZip64.Off instead.

                zipOutputStream.PutNextEntry(entry);

                int count = fs.Read(buffer, 0, buffer.Length);
                while (count > 0)
                {
                    zipOutputStream.Write(buffer, 0, count);
                    count = fs.Read(buffer, 0, buffer.Length);
                    if (!System.Web.HttpContext.Current.Response.IsClientConnected)
                    {
                        break;
                    }
                    System.Web.HttpContext.Current.Response.Flush();
                }
                fs.Close();
            }
            zipOutputStream.Close();

            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();
        }
Beispiel #5
0
 //
 public static byte[] Compress(byte[] data, string fileName)
 {
     // Compress
     using (MemoryStream fsOut = new MemoryStream())
     {
         using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut))
         {
             zipStream.SetLevel(3);
             ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
             newEntry.DateTime = DateTime.UtcNow;
             newEntry.Size     = data.Length;
             zipStream.PutNextEntry(newEntry);
             zipStream.Write(data, 0, data.Length);
             zipStream.Finish();
             zipStream.Close();
         }
         return(fsOut.ToArray());
     }
 }
Beispiel #6
0
        /// <summary>
        /// Create a zip file of the supplied file names and string data source
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully creating the zip file.</returns>
        public static bool ZipData(string zipPath, Dictionary<string, string> filenamesAndData)
        {
            var success = true;
            var buffer = new byte[4096];

            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var filename in filenamesAndData.Keys)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(filename);
                        //Get a Byte[] of the file data:
                        var file = Encoding.Default.GetBytes(filenamesAndData[filename]);
                        stream.PutNextEntry(entry);

                        using (var ms = new MemoryStream(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = ms.Read(buffer, 0, buffer.Length);
                                stream.Write(buffer, 0, sourceBytes);
                            }
                            while (sourceBytes > 0);
                        }
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error(err);
                success = false;
            }
            return success;
        }
Beispiel #7
0
        /// <summary>
        /// Create a zip file of the supplied file names and string data source
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully creating the zip file.</returns>
        public static bool ZipData(string zipPath, Dictionary <string, string> filenamesAndData)
        {
            var success = true;
            var buffer  = new byte[4096];

            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var filename in filenamesAndData.Keys)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(filename);
                        //Get a Byte[] of the file data:
                        var file = Encoding.Default.GetBytes(filenamesAndData[filename]);
                        stream.PutNextEntry(entry);

                        using (var ms = new MemoryStream(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = ms.Read(buffer, 0, buffer.Length);
                                stream.Write(buffer, 0, sourceBytes);
                            }while (sourceBytes > 0);
                        }
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error(err);
                success = false;
            }
            return(success);
        }
Beispiel #8
0
        /// <summary>
        /// Compress a given file and delete the original file. Automatically rename the file to name.zip.
        /// </summary>
        /// <param name="textPath">Path of the original file</param>
        /// <param name="zipEntryName">The name of the entry inside the zip file</param>
        /// <param name="deleteOriginal">Boolean flag to delete the original file after completion</param>
        /// <returns>String path for the new zip file</returns>
        public static string Zip(string textPath, string zipEntryName, bool deleteOriginal = true)
        {
            var zipPath = "";

            try
            {
                var buffer = new byte[4096];
                zipPath = textPath.Replace(".csv", ".zip");
                zipPath = zipPath.Replace(".txt", ".zip");
                //Open the zip:
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    //Zip the text file.
                    var entry = new ZipEntry(zipEntryName);
                    stream.PutNextEntry(entry);

                    using (var fs = File.OpenRead(textPath))
                    {
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            stream.Write(buffer, 0, sourceBytes);
                        }while (sourceBytes > 0);
                    }
                    //Close stream:
                    stream.Finish();
                    stream.Close();
                }
                //Delete the old text file:
                if (deleteOriginal)
                {
                    File.Delete(textPath);
                }
            }
            catch (Exception err)
            {
                Log.Error(err);
            }
            return(zipPath);
        }
Beispiel #9
0
        /// <summary>
        /// Create a zip file of the supplied file names and data using a byte array
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully saving the file</returns>
        public static bool ZipData(string zipPath, IEnumerable <KeyValuePair <string, byte[]> > filenamesAndData)
        {
            var success = true;
            var buffer  = new byte[4096];

            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var file in filenamesAndData)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(file.Key);
                        //Get a Byte[] of the file data:
                        stream.PutNextEntry(entry);

                        using (var ms = new MemoryStream(file.Value))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = ms.Read(buffer, 0, buffer.Length);
                                stream.Write(buffer, 0, sourceBytes);
                            }while (sourceBytes > 0);
                        }
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error("QC.Data.ZipData(): " + err.Message);
                success = false;
            }
            return(success);
        }
Beispiel #10
0
        /// <summary>
        /// Compacta a lista de Arquivos criando o arquivo zip passado como parâmetro
        /// </summary>
        /// <param name="filesName">Lista de arquivos a serem incluidos no .zip</param>
        /// <param name="strArquivoZip">Nome do arquivo .zip</param>
        public void compacta(ref System.Collections.ArrayList filesName, string strArquivoZip)
        {
            try
            {
                ICSharpCode.SharpZipLib.Checksums.Crc32     clsCrc          = new ICSharpCode.SharpZipLib.Checksums.Crc32();
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream clsZipOutStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(strArquivoZip));

                clsZipOutStream.SetLevel(m_nNivelCompressao);

                foreach (string file in filesName)
                {
                    System.IO.FileStream fs = System.IO.File.OpenRead(file);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file);

                    entry.DateTime = DateTime.Now;

                    entry.Size = fs.Length;
                    fs.Close();

                    clsCrc.Reset();
                    clsCrc.Update(buffer);

                    entry.Crc = clsCrc.Value;

                    clsZipOutStream.PutNextEntry(entry);

                    clsZipOutStream.Write(buffer, 0, buffer.Length);
                }
                clsZipOutStream.Finish();
                clsZipOutStream.Close();
            }
            catch (Exception err)
            {
                Object erro = err;
                m_cls_ter_tratadorErro.trataErro(ref erro);
            }
        }
		internal void AddResources(Dictionary<string, List<ResourceItem>> resources, bool compressedResources)
		{
			Tracer.Info(Tracer.Compiler, "CompilerClassLoader adding resources...");

			// BUG we need to call GetTypeWrapperFactory() to make sure that the assemblyBuilder is created (when building an empty target)
			ModuleBuilder moduleBuilder = this.GetTypeWrapperFactory().ModuleBuilder;
			Dictionary<string, Dictionary<string, ResourceItem>> jars = new Dictionary<string, Dictionary<string, ResourceItem>>();

			foreach (KeyValuePair<string, List<ResourceItem>> kv in resources)
			{
				foreach (ResourceItem item in kv.Value)
				{
					int count = 0;
					string jarName = item.jar;
				retry:
					Dictionary<string, ResourceItem> jar;
					if (!jars.TryGetValue(jarName, out jar))
					{
						jar = new Dictionary<string, ResourceItem>();
						jars.Add(jarName, jar);
					}
					if (jar.ContainsKey(kv.Key))
					{
						jarName = Path.GetFileNameWithoutExtension(item.jar) + "-" + (count++) + Path.GetExtension(item.jar);
						goto retry;
					}
					jar.Add(kv.Key, item);
				}
			}

			foreach (KeyValuePair<string, Dictionary<string, ResourceItem>> jar in jars)
			{
				MemoryStream mem = new MemoryStream();
				using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(mem))
				{
					foreach (KeyValuePair<string, ResourceItem> kv in jar.Value)
					{
						ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(kv.Key);
						if (kv.Value.zipEntry == null)
						{
							zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored;
						}
						else
						{
							zipEntry.Comment = kv.Value.zipEntry.Comment;
							zipEntry.CompressionMethod = kv.Value.zipEntry.CompressionMethod;
							zipEntry.DosTime = kv.Value.zipEntry.DosTime;
							zipEntry.ExternalFileAttributes = kv.Value.zipEntry.ExternalFileAttributes;
							zipEntry.ExtraData = kv.Value.zipEntry.ExtraData;
							zipEntry.Flags = kv.Value.zipEntry.Flags;
						}
						if (compressedResources || zipEntry.CompressionMethod != ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored)
						{
							zip.SetLevel(9);
							zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated;
						}
						zip.PutNextEntry(zipEntry);
						if (kv.Value.data != null)
						{
							zip.Write(kv.Value.data, 0, kv.Value.data.Length);
						}
						zip.CloseEntry();
					}
				}
				mem = new MemoryStream(mem.ToArray());
				string name = jar.Key;
				if (options.targetIsModule)
				{
					name = Path.GetFileNameWithoutExtension(name) + "-" + moduleBuilder.ModuleVersionId.ToString("N") + Path.GetExtension(name);
				}
				jarList.Add(name);
				moduleBuilder.DefineManifestResource(name, mem, ResourceAttributes.Public);
			}
		}
        public void ZipAdminFile(string strFile, List <string> filesExtra)
        {
            if (File.Exists(strFile))
            {
                if (GetConfig().ZipAfterIndexed == true)
                {
                    try
                    {
                        string zipFilePath = Path.ChangeExtension(strFile, ".zip");
                        if (File.Exists(zipFilePath))
                        {
                            File.Delete(zipFilePath);
                        }

                        if (filesExtra == null)
                        {
                            filesExtra = new List <string>();
                        }
                        if (strFile != null)
                        {
                            filesExtra.Add(strFile);
                        }

                        ICSharpCode.SharpZipLib.Zip.ZipOutputStream strmZipOutputStream = default(ICSharpCode.SharpZipLib.Zip.ZipOutputStream);
                        strmZipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFilePath));

                        if (GetConfig().CollapseFolders)
                        {
                            // minus.gif
                            string f1 = Application.StartupPath + Path.DirectorySeparatorChar + "plus.gif";
                            if (File.Exists(f1))
                            {
                                filesExtra.Add(f1);
                            }
                            string f2 = Application.StartupPath + Path.DirectorySeparatorChar + "minus.gif";
                            if (File.Exists(f2))
                            {
                                filesExtra.Add(f2);
                            }
                        }

                        if (File.Exists(GetConfig().LogoPath))
                        {
                            filesExtra.Add(GetConfig().LogoPath);
                        }

                        foreach (string filePath in filesExtra)
                        {
                            FileStream strmFile  = File.OpenRead(filePath);
                            byte[]     abyBuffer = new byte[(int)strmFile.Length - 1 + 1];
                            strmFile.Read(abyBuffer, 0, abyBuffer.Length);

                            ICSharpCode.SharpZipLib.Zip.ZipEntry objZipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filePath));
                            objZipEntry.DateTime = DateTime.Now;
                            objZipEntry.Size     = strmFile.Length;
                            strmFile.Close();

                            strmZipOutputStream.PutNextEntry(objZipEntry);

                            strmZipOutputStream.Write(abyBuffer, 0, abyBuffer.Length);
                        }

                        ///'''''''''''''''''''''''''''''''''
                        // Finally Close strmZipOutputStream
                        ///'''''''''''''''''''''''''''''''''
                        strmZipOutputStream.Finish();
                        strmZipOutputStream.Close();

                        if (GetConfig().ZipAndDeleteFile == true)
                        {
                            File.Delete(strFile);
                        }
                    }
                    catch (System.UnauthorizedAccessException ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }
                }
            }
        }
		BuildResult Zip (IProgressMonitor monitor, MoonlightProject proj, DotNetProjectConfiguration conf, ConfigurationSelector slnConf)
		{
			var xapName = GetXapName (proj, conf);
			
			var src = new List<string> ();
			var targ = new List<string> ();
			
			src.Add (conf.CompiledOutputName);
			targ.Add (conf.CompiledOutputName.FileName);
			
			// FIXME: this is a hack for the Mono Soft Debugger. In future the mdb files should be *beside* the xap,
			// when sdb supports that model. Note that there's no point doing this for pdb files, because the debuggers 
			// that read pdb files don't expect them to be in the xap.
			var doSdbCopy = conf.DebugMode && proj.TargetRuntime is MonoDevelop.Core.Assemblies.MonoTargetRuntime;
			
			if (doSdbCopy) {
				FilePath mdb = conf.CompiledOutputName + ".mdb";
				if (File.Exists (mdb)) {
					src.Add (mdb);
					targ.Add (mdb.FileName);
				}
			}

			if (proj.GenerateSilverlightManifest) {
				src.Add (conf.OutputDirectory.Combine ("AppManifest.xaml"));
				targ.Add ("AppManifest.xaml");
			}

			foreach (ProjectFile pf in proj.Files) {
				if (pf.BuildAction == BuildAction.Content) {
					src.Add (pf.FilePath);
					targ.Add (pf.ProjectVirtualPath);
				}
			}
			
			BuildResult res = new BuildResult ();

			// The "copy to output" files don't seem to be included in xaps, so we can't use project.GetSupportFiles.
			// Instead we need to iterate over the refs and handle them manually.
			foreach (ProjectReference pr in proj.References) {
				if (pr.LocalCopy) {
					var pk = pr.Package;
					if (pk == null || !pk.IsFrameworkPackage || pk.Name.EndsWith ("-redist")) {
						string err = pr.ValidationErrorMessage;
						if (!String.IsNullOrEmpty (err)) {
							string msg = String.Format ("Could not add reference '{0}' to '{1}': {2}",
							                            pr.Reference, xapName.FileName, err);
							res.AddError (msg);
							monitor.Log.WriteLine (msg);
							continue;
						}
						foreach (string s in pr.GetReferencedFileNames (slnConf)) {
							src.Add (s);
							targ.Add (Path.GetFileName (s));
							
							if (doSdbCopy && s.EndsWith (".dll")) {
								FilePath mdb = s + ".mdb";
								if (File.Exists (mdb)) {
									src.Add (mdb);
									targ.Add (mdb.FileName);
								}
							}
						}
					}
				}
			}
			
			if (res.ErrorCount > 0) {
				res.FailedBuildCount++;
				return res;
			}
			
			if (File.Exists (xapName)) {
				DateTime lastMod = File.GetLastWriteTime (xapName);
				bool needsWrite = false;
				foreach (string file in src) {
					if (File.GetLastWriteTime (file) > lastMod) {
						needsWrite = true;
						break;
					}
				}
				if (!needsWrite)
					return null;
			}
			
			monitor.Log.WriteLine ("Compressing XAP file...");
			
			try {
				using (FileStream fs = new FileStream (xapName, FileMode.Create)) {
					var zipfile = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream (fs);
					zipfile.SetLevel (9);
					
					byte[] buffer = new byte[4096];
					
					for (int i = 0; i < src.Count && !monitor.IsCancelRequested; i++) {
						zipfile.PutNextEntry (new ICSharpCode.SharpZipLib.Zip.ZipEntry (targ[i]));
						using (FileStream inStream = File.OpenRead (src[i])) {
							int readCount;
							do {
								readCount = inStream.Read (buffer, 0, buffer.Length);
								zipfile.Write (buffer, 0, readCount);
							} while (readCount > 0);
						}
					}
					if (!monitor.IsCancelRequested) {
						zipfile.Finish ();
						zipfile.Close ();
					}
				}
			} catch (IOException ex) {
				monitor.ReportError ("Error writing xap file.", ex);
				res.AddError ("Error writing xap file:" + ex.ToString ());
				res.FailedBuildCount++;
				
				try {
					if (File.Exists (xapName))                                                               
						File.Delete (xapName);
				} catch {}
				
				return res;
			}
			
			if (monitor.IsCancelRequested) {
				try {
					if (File.Exists (xapName))                                                               
						File.Delete (xapName);
				} catch {}
			}
			
			return res;
		}
Beispiel #14
0
 private void menuExportTeamData_Click(object sender, EventArgs e)
 {
     SaveFileDialog d = new SaveFileDialog();
     d.AddExtension = true;
     d.DefaultExt = ".zip";
     d.Filter = T("Tutti i file ZIP (*.zip)")+"|*.zip";
     d.FileName = "RMO-Team-Data-" + DateTime.Now.ToString("yyyy-MM-dd") + ".zip";
     d.InitialDirectory = My.Dir.Desktop;
     d.OverwritePrompt = true;
     d.Title = T("Nome del file da esportare");
     if (d.ShowDialog() == DialogResult.OK)
     {
         try
         {
             string[] filenames = System.IO.Directory.GetFiles(PATH_HISTORY, "*.team");
             progressBar.Value = 0;
             progressBar.Maximum = filenames.Length;
             using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(d.FileName)))
             {
                 s.SetLevel(9);
                 byte[] buffer = new byte[4096];
                 foreach (string file in filenames)
                 {
                     ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(System.IO.Path.GetFileName(file));
                     entry.DateTime = DateTime.Now;
                     s.PutNextEntry(entry);
                     using (System.IO.FileStream fs = System.IO.File.OpenRead(file))
                     {
                         int sourceBytes;
                         do
                         {
                             sourceBytes = fs.Read(buffer, 0, buffer.Length);
                             s.Write(buffer, 0, sourceBytes);
                         }
                         while (sourceBytes > 0);
                     }
                     progressBar.Value++;
                 }
                 s.Finish();
                 s.Close();
                 lStatus.Text = T("Esportazione del backup ultimata correttamente!");
             }
         }
         catch (Exception ex) { My.Box.Errore(T("Errore durante l'esportazione del backup")+"\r\n"+ex.Message); }
         progressBar.Value = 0;
     }
 }
Beispiel #15
0
        // 패치할 파일들을 zip 으로 압축한다.
        List <PatchFileInfo> PatchFilesCompression_Zip()
        {
            List <PatchFileInfo> PatchFileInfoList = new List <PatchFileInfo>();
            PatchFileInfo        patchfileinfo     = new PatchFileInfo();

            // 사용법 http://dobon.net/vb/dotnet/links/sharpziplib.html
            // SharpZipLib 사이트 http://www.icsharpcode.net/OpenSource/SharpZipLib/
            try
            {
                this.Cursor = Cursors.WaitCursor;

                //ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();

                string zipFullPathName      = textBoxPackingFilesFolder.Text + @"\" + PackingFileName + ".zip";
                System.IO.FileStream writer = new System.IO.FileStream(zipFullPathName, System.IO.FileMode.Create,
                                                                       System.IO.FileAccess.Write, System.IO.FileShare.Write);
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream zos = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(writer);

                // 압축레벨을 설정
                //zos.SetLevel(6);
                // 패스워드를 설정한다.
                //zos.Password = "******";

                foreach (string file in PatchFileList)
                {
                    int    Substringindex = textBoxNextVerFolder.Text.Length;
                    string f = file.Substring(Substringindex + 1);

                    ICSharpCode.SharpZipLib.Zip.ZipEntry ze = new ICSharpCode.SharpZipLib.Zip.ZipEntry(f);

                    System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read,
                                                                       System.IO.FileShare.Read);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    fs.Close();

                    // CRC를 설정한다
                    //crc.Reset();
                    //crc.Update(buffer);
                    //ze.Crc = crc.Value;

                    // 사이즈를 설정한다
                    ze.Size = buffer.Length;

                    // 시간을 설정한다
                    ze.DateTime = DateTime.Now;

                    // 새로운 파일을 추가
                    zos.PutNextEntry(ze);

                    // 쓰기
                    zos.Write(buffer, 0, buffer.Length);
                }

                zos.Close();
                writer.Close();

                patchfileinfo.FileName = new FileInfo(zipFullPathName).Name;
                patchfileinfo.FileCRC  = GetCRC(zipFullPathName);
                patchfileinfo.FileSize = new FileInfo(zipFullPathName).Length;

                PatchFileInfoList.Add(patchfileinfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

            return(PatchFileInfoList);
        }
Beispiel #16
0
        BuildResult Zip(IProgressMonitor monitor, MoonlightProject proj, DotNetProjectConfiguration conf, ConfigurationSelector slnConf)
        {
            var xapName = GetXapName(proj, conf);

            var src  = new List <string> ();
            var targ = new List <string> ();

            src.Add(conf.CompiledOutputName);
            targ.Add(conf.CompiledOutputName.FileName);

            // FIXME: this is a hack for the Mono Soft Debugger. In future the mdb files should be *beside* the xap,
            // when sdb supports that model. Note that there's no point doing this for pdb files, because the debuggers
            // that read pdb files don't expect them to be in the xap.
            var doSdbCopy = conf.DebugMode && proj.TargetRuntime is MonoDevelop.Core.Assemblies.MonoTargetRuntime;

            if (doSdbCopy)
            {
                FilePath mdb = conf.CompiledOutputName + ".mdb";
                if (File.Exists(mdb))
                {
                    src.Add(mdb);
                    targ.Add(mdb.FileName);
                }
            }

            if (proj.GenerateSilverlightManifest)
            {
                src.Add(conf.OutputDirectory.Combine("AppManifest.xaml"));
                targ.Add("AppManifest.xaml");
            }

            foreach (ProjectFile pf in proj.Files)
            {
                if (pf.BuildAction == BuildAction.Content)
                {
                    src.Add(pf.FilePath);
                    targ.Add(pf.ProjectVirtualPath);
                }
            }

            BuildResult res = new BuildResult();

            // The "copy to output" files don't seem to be included in xaps, so we can't use project.GetSupportFiles.
            // Instead we need to iterate over the refs and handle them manually.
            foreach (ProjectReference pr in proj.References)
            {
                if (pr.LocalCopy)
                {
                    var pk = pr.Package;
                    if (pk == null || !pk.IsFrameworkPackage || pk.Name.EndsWith("-redist"))
                    {
                        string err = pr.ValidationErrorMessage;
                        if (!String.IsNullOrEmpty(err))
                        {
                            string msg = String.Format("Could not add reference '{0}' to '{1}': {2}",
                                                       pr.Reference, xapName.FileName, err);
                            res.AddError(msg);
                            monitor.Log.WriteLine(msg);
                            continue;
                        }
                        foreach (string s in pr.GetReferencedFileNames(slnConf))
                        {
                            src.Add(s);
                            targ.Add(Path.GetFileName(s));

                            if (doSdbCopy && s.EndsWith(".dll"))
                            {
                                FilePath mdb = s + ".mdb";
                                if (File.Exists(mdb))
                                {
                                    src.Add(mdb);
                                    targ.Add(mdb.FileName);
                                }
                            }
                        }
                    }
                }
            }

            if (res.ErrorCount > 0)
            {
                res.FailedBuildCount++;
                return(res);
            }

            if (File.Exists(xapName))
            {
                DateTime lastMod    = File.GetLastWriteTime(xapName);
                bool     needsWrite = false;
                foreach (string file in src)
                {
                    if (File.GetLastWriteTime(file) > lastMod)
                    {
                        needsWrite = true;
                        break;
                    }
                }
                if (!needsWrite)
                {
                    return(null);
                }
            }

            monitor.Log.WriteLine("Compressing XAP file...");

            try {
                using (FileStream fs = new FileStream(xapName, FileMode.Create)) {
                    var zipfile = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fs);
                    zipfile.SetLevel(9);

                    byte[] buffer = new byte[4096];

                    for (int i = 0; i < src.Count && !monitor.IsCancelRequested; i++)
                    {
                        zipfile.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry(targ[i]));
                        using (FileStream inStream = File.OpenRead(src[i])) {
                            int readCount;
                            do
                            {
                                readCount = inStream.Read(buffer, 0, buffer.Length);
                                zipfile.Write(buffer, 0, readCount);
                            } while (readCount > 0);
                        }
                    }
                    if (!monitor.IsCancelRequested)
                    {
                        zipfile.Finish();
                        zipfile.Close();
                    }
                }
            } catch (IOException ex) {
                monitor.ReportError("Error writing xap file.", ex);
                res.AddError("Error writing xap file:" + ex.ToString());
                res.FailedBuildCount++;

                try {
                    if (File.Exists(xapName))
                    {
                        File.Delete(xapName);
                    }
                } catch {}

                return(res);
            }

            if (monitor.IsCancelRequested)
            {
                try {
                    if (File.Exists(xapName))
                    {
                        File.Delete(xapName);
                    }
                } catch {}
            }

            return(res);
        }
Beispiel #17
0
        } // End Sub CreateExe

        // http://blogs.msdn.com/b/dotnetinterop/archive/2008/06/04/dotnetzip-now-can-save-directly-to-asp-net-response-outputstream.aspx

        // This will accumulate each of the files named in the fileList into a zip file,
        // and stream it to the browser.
        // This approach writes directly to the Response OutputStream.
        // The browser starts to receive data immediately which should avoid timeout problems.
        // This also avoids an intermediate memorystream, saving memory on large files.
        //
        public static void DownloadZipToBrowser(System.Collections.Generic.List <string> zipFileList)
        {
            System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;

            Response.ClearContent();
            Response.ClearHeaders();
            Response.Clear();

            Response.Buffer = false;

            Response.ContentType = "application/zip";
            // If the browser is receiving a mangled zipfile, IIS Compression may cause this problem. Some members have found that
            //    Response.ContentType = "application/octet-stream"     has solved this. May be specific to Internet Explorer.

            Response.AppendHeader("content-disposition", "attachment; filename=\"Download.zip\"");
            // Response.CacheControl = "Private";
            // Response.Cache.SetExpires(System.DateTime.Now.AddMinutes(3)); // or put a timestamp in the filename in the content-disposition

            // http://stackoverflow.com/questions/9303919/pack-empty-directory-with-sharpziplib


            byte[] buffer = new byte[4096];

            using (ZipOutputStream zipOutputStream = new ZipOutputStream(Response.OutputStream))
            {
                zipOutputStream.SetLevel(3); //0-9, 9 being the highest level of compression

                // zipOutputStream.Dispose

                // Empty folder...
                foreach (string directoryName in zipFileList)
                {
                    string   dname = "myfolder/";
                    ZipEntry entry = new ZipEntry(dname);
                    // ZipEntry entry = new ZipEntry(ZipEntry.CleanName(dname));
                    // entry.Size = fs.Length;
                    zipOutputStream.PutNextEntry(entry);
                } // Next directoryName


                foreach (string fileName in zipFileList)
                {
                    // or any suitable inputstream
                    using (System.IO.Stream fs = System.IO.File.OpenRead(fileName))
                    {
                        ZipEntry entry = new ZipEntry(ZipEntry.CleanName(fileName));
                        entry.Size = fs.Length;


                        // Setting the Size provides WinXP built-in extractor compatibility,
                        // but if not available, you can set zipOutputStream.UseZip64 = UseZip64.Off instead.
                        zipOutputStream.PutNextEntry(entry);

                        int count = fs.Read(buffer, 0, buffer.Length);
                        while (count > 0)
                        {
                            zipOutputStream.Write(buffer, 0, count);
                            count = fs.Read(buffer, 0, buffer.Length);

                            if (!Response.IsClientConnected)
                            {
                                break;
                            }

                            Response.Flush();
                        } // Whend

                        fs.Close();
                    } // End Using fs
                }     // Next fileName

                zipOutputStream.Close();
            } // End Using zipOutputStream

            Response.Flush();
            Response.End();
        } // End Function DownloadZipToBrowser
Beispiel #18
0
 public static void CreateVersionWycFile()
 {
     {
         var fileStream      = System.IO.File.Create("client.wyc");
         var zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fileStream);
         {
             var iucMemoryStream = new System.IO.MemoryStream();
             {
                 //var fileStream = System.IO.File.Create("iuclient.iuc");
                 var fw = new wyUpdate.FileWriter(iucMemoryStream);
                 fw.WriteHeader("IUCDFV2");
                 fw.WriteDeprecatedString(0x01, "RealmPlayers.com");           //Company Name
                 fw.WriteDeprecatedString(0x02, "VF_WoWLauncher");             //Product Name
                 fw.WriteDeprecatedString(0x03, StaticValues.LauncherVersion); //Installed Version
                 //fw.WriteDeprecatedString(0x03, "0.9"); //Installed Version
                 fw.WriteString(0x0A, "TestAnything");                         //GUID of the product
                 if (Settings.Instance.UpdateToBeta == true)
                 {
                     fw.WriteDeprecatedString(0x04, "ftp://[email protected]:5511/Updates/VF_WowLauncher/BetaUpdate.wys"); //Server File Site(s)
                 }
                 else
                 {
                     fw.WriteDeprecatedString(0x04, "ftp://[email protected]:5511/Updates/VF_WowLauncher/Update.wys"); //Server File Site(s)
                 }
                 fw.WriteDeprecatedString(0x09, "ftp://[email protected]:5511/Updates/wyUpdate/Update.wys");           //wyUpdate Server Site(s) (can add any number of theese)
                 fw.WriteDeprecatedString(0x11, "Left");                                                                                 //Header Image Alignment Either "Left", "Right", "Fill"
                 fw.WriteInt(0x12, 4);                                                                                                   //Header text indent
                 fw.WriteDeprecatedString(0x13, "Black");                                                                                //Header text color (Black, White, Red etc etc etc)
                 fw.WriteDeprecatedString(0x14, "HeaderImage.png");                                                                      //Header filename
                 fw.WriteDeprecatedString(0x15, "LeftImage.png");                                                                        //Side image filename
                 fw.WriteDeprecatedString(0x18, "en-US");                                                                                //Language Culture (e.g. en-US or fr-FR)
                 fw.WriteBool(0x17, false);                                                                                              //Hide header divider? (default = false)
                 fw.WriteBool(0x19, false);                                                                                              //Close wyUpdate on successful update
                 fw.WriteString(0x1A, "VF_WoWLauncher Updater");                                                                         //Custom wyUpdate title bar
                 //WriteFiles.WriteString(fileStream, 0x1B, "DilaPublicSignKey"); //Public sign key -- DENNA MÅSTE VARA KORREKT ANNARS FAILAR SHA1!!!!!
                 iucMemoryStream.WriteByte(0xFF);
                 //fileStream.Close();
             }
             var byteArray = iucMemoryStream.ToArray();
             var newEntry  = new ICSharpCode.SharpZipLib.Zip.ZipEntry("iuclient.iuc");
             newEntry.Size = byteArray.Length;
             zipOutputStream.PutNextEntry(newEntry);
             zipOutputStream.Write(byteArray, 0, byteArray.Length);
             zipOutputStream.CloseEntry();
         }
         {
             var newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("HeaderImage.png");
             newEntry.Size = Properties.Resources.HeaderImagepng.Length;
             zipOutputStream.PutNextEntry(newEntry);
             zipOutputStream.Write(Properties.Resources.HeaderImagepng, 0, Properties.Resources.HeaderImagepng.Length);
             zipOutputStream.CloseEntry();
         }
         {
             var newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("LeftImage.png");
             newEntry.Size = Properties.Resources.LeftImagepng.Length;
             zipOutputStream.PutNextEntry(newEntry);
             zipOutputStream.Write(Properties.Resources.LeftImagepng, 0, Properties.Resources.LeftImagepng.Length);
             zipOutputStream.CloseEntry();
         }
         zipOutputStream.Close();
         fileStream.Close();
         //var newZipFile = ICSharpCode.SharpZipLib.Zip.ZipFile.Create("client.wyc");
         //newZipFile.BeginUpdate();
         //newZipFile.Add("iuclient.iuc");
         //newZipFile.Add(new ICSharpCode.SharpZipLib.Zip.ZipEntry(
         //newZipFile.Add(Properties.Resources.HeaderImagepng, "HeaderImage.png");
         //newZipFile.Add("LeftImage.png");
         //newZipFile.CommitUpdate();
         //newZipFile.Close();
     }
 }
Beispiel #19
0
        private static void Zip(string[] files, ICSharpCode.SharpZipLib.Zip.ZipOutputStream s)
        {
            List <string> rootPaths = new List <string>();

            ICSharpCode.SharpZipLib.Zip.ZipEntry entry = null;
            System.IO.FileStream fs = null;
            ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
            try
            {
                ////创建当前文件夹
                //entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("/");  //加上 “/” 才会当成是文件夹创建
                //s.PutNextEntry(entry);
                //s.Flush();
                foreach (string file in files)
                {
                    if (System.IO.Directory.Exists(file))
                    {
                        if (file.Split('\\').Count() > 1)
                        {
                            rootPaths.Add(file);
                            entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Split('\\').Last() + "/");  //加上 “/” 才会当成是文件夹创建
                            s.PutNextEntry(entry);
                            s.Flush();
                        }
                        continue;
                    }

                    //打开压缩文件
                    fs = System.IO.File.OpenRead(file);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    var zipfilename = System.IO.Path.GetFileName(file);
                    foreach (var rootPath in rootPaths)
                    {
                        var _index = file.IndexOf(rootPath);
                        if (_index >= 0)
                        {
                            zipfilename = rootPath.Split('\\').Last() + "\\" + System.IO.Path.GetFileName(file);
                            break;
                        }
                    }
                    entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipfilename)
                    {
                        DateTime = DateTime.Now,
                        Size     = fs.Length
                    };
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
                if (entry != null)
                {
                    entry = null;
                }
                GC.Collect();
            }
        }
Beispiel #20
0
 public static void Zip(string data, string zipPath, string zipEntry)
 {
     using (var stream = new ZipOutputStream(File.Create(zipPath)))
     {
         var entry = new ZipEntry(zipEntry);
         stream.PutNextEntry(entry);
         var buffer = new byte[4096];
         using (var dataReader = new MemoryStream(Encoding.Default.GetBytes(data)))
         {
             int sourceBytes;
             do
             {
                 sourceBytes = dataReader.Read(buffer, 0, buffer.Length);
                 stream.Write(buffer, 0, sourceBytes);
             }
             while (sourceBytes > 0);
         }
     }
 }
Beispiel #21
0
        /// <summary>
        /// Compress a given file and delete the original file. Automatically rename the file to name.zip.
        /// </summary>
        /// <param name="textPath">Path of the original file</param>
        /// <param name="deleteOriginal">Boolean flag to delete the original file after completion</param>
        /// <returns>String path for the new zip file</returns>
        public static string Zip(string textPath, bool deleteOriginal = true)
        {
            var zipPath = "";

            try
            {
                var buffer = new byte[4096];
                zipPath = textPath.Replace(".csv", ".zip");
                zipPath = zipPath.Replace(".txt", ".zip");
                //Open the zip:
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    //Zip the text file.
                    var entry = new ZipEntry(Path.GetFileName(textPath));
                    stream.PutNextEntry(entry);

                    using (var fs = File.OpenRead(textPath))
                    {
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            stream.Write(buffer, 0, sourceBytes);
                        }
                        while (sourceBytes > 0);
                    }
                    //Close stream:
                    stream.Finish();
                    stream.Close();
                }
                //Delete the old text file:
                if (deleteOriginal) File.Delete(textPath);
            }
            catch (Exception err)
            {
                Log.Error("QC.Data.Zip(): " + err.Message);
            }
            return zipPath;
        }
        public void ZipAdminFile(string strFile, List<string> filesExtra)
        {
            if (File.Exists(strFile))
            {
                if (GetConfig().ZipAfterIndexed == true)
                {
                    try
                    {
                        string zipFilePath = Path.ChangeExtension(strFile, ".zip");
                        if (File.Exists(zipFilePath)) File.Delete(zipFilePath);

                        if (filesExtra == null)
                        {
                            filesExtra = new List<string>();
                        }
                        if (strFile != null)
                        {
                            filesExtra.Add(strFile);
                        }

                        ICSharpCode.SharpZipLib.Zip.ZipOutputStream strmZipOutputStream = default(ICSharpCode.SharpZipLib.Zip.ZipOutputStream);
                        strmZipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFilePath));

                        if (GetConfig().CollapseFolders)
                        {
                            // minus.gif
                            string f1 = Application.StartupPath + Path.DirectorySeparatorChar + "plus.gif";
                            if (File.Exists(f1)) filesExtra.Add(f1);
                            string f2 = Application.StartupPath + Path.DirectorySeparatorChar + "minus.gif";
                            if (File.Exists(f2)) filesExtra.Add(f2);
                        }

                        if (File.Exists(GetConfig().LogoPath))
                        {
                            filesExtra.Add(GetConfig().LogoPath);
                        }

                        foreach (string filePath in filesExtra)
                        {
                            FileStream strmFile = File.OpenRead(filePath);
                            byte[] abyBuffer = new byte[(int)strmFile.Length - 1 + 1];
                            strmFile.Read(abyBuffer, 0, abyBuffer.Length);

                            ICSharpCode.SharpZipLib.Zip.ZipEntry objZipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filePath));
                            objZipEntry.DateTime = DateTime.Now;
                            objZipEntry.Size = strmFile.Length;
                            strmFile.Close();

                            strmZipOutputStream.PutNextEntry(objZipEntry);

                            strmZipOutputStream.Write(abyBuffer, 0, abyBuffer.Length);
                        }

                        ///'''''''''''''''''''''''''''''''''
                        // Finally Close strmZipOutputStream
                        ///'''''''''''''''''''''''''''''''''
                        strmZipOutputStream.Finish();
                        strmZipOutputStream.Close();

                        if (GetConfig().ZipAndDeleteFile == true)
                        {
                            File.Delete(strFile);
                        }
                    }
                    catch (System.UnauthorizedAccessException ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }
                }
            }
        }
Beispiel #23
0
        /// <summary>
        /// Create a zip file of the supplied file names and data using a byte array
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully saving the file</returns>
        public static bool ZipData(string zipPath, IEnumerable<KeyValuePair<string, byte[]>> filenamesAndData)
        {
            var success = true;
            var buffer = new byte[4096];

            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var file in filenamesAndData)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(file.Key);
                        //Get a Byte[] of the file data:
                        stream.PutNextEntry(entry);

                        using (var ms = new MemoryStream(file.Value))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = ms.Read(buffer, 0, buffer.Length);
                                stream.Write(buffer, 0, sourceBytes);
                            }
                            while (sourceBytes > 0);
                        }
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error("QC.Data.ZipData(): " + err.Message);
                success = false;
            }
            return success;
        }
Beispiel #24
0
        private static void compress_zip()
        {
            string zipPath   = bset.zip_path;
            string zipFolder = bset.tmp_folder_path;

            //Write ZIP Stream.
            FileStream writer = new FileStream(zipPath, FileMode.Create, FileAccess.Write);

            //Build ZipOutputStream.
            ICSharpCode.SharpZipLib.Zip.ZipOutputStream zos = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(writer);

            //Set compress levels.
            if ((0 <= bset.compress) | (9 >= bset.compress))
            {
                zos.SetLevel(bset.compress);
            }
            else
            {
                zos.SetLevel(9);
            }

            //Get folders.
            ICSharpCode.SharpZipLib.Zip.ZipNameTransform nameTrans =
                new ICSharpCode.SharpZipLib.Zip.ZipNameTransform(zipFolder);

            foreach (string file in Directory.EnumerateFiles(zipFolder, "*", System.IO.SearchOption.AllDirectories))
            {
                if (file == bset.zip_path)
                {
                    continue;
                }

                // Set file name.
                string f = nameTrans.TransformFile(file);
                ICSharpCode.SharpZipLib.Zip.ZipEntry ze =
                    new ICSharpCode.SharpZipLib.Zip.ZipEntry(f);

                // Set file informations.
                FileInfo fi = new System.IO.FileInfo(file);
                ze.DateTime = fi.LastAccessTime;
                ze.ExternalFileAttributes = (int)fi.Attributes;
                ze.Size          = fi.Length;
                ze.IsUnicodeText = true;
                zos.PutNextEntry(ze);

                // Load files.
                try
                {
                    FileStream fs     = new System.IO.FileStream(file, FileMode.Open, FileAccess.Read);
                    byte[]     buffer = new byte[2048];
                    int        len;
                    while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        zos.Write(buffer, 0, len);
                    }
                    fs.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(" - Error: " + file + " [" + ex.Message + "]");
                    continue;
                }
            }
            // Close objects.
            zos.Finish();
            zos.Close();
            writer.Close();
        }