Пример #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;
            }
        }
Пример #2
0
        public static MemoryStream CreateToMemoryStream(MemoryStream memStreamIn, string zipEntryName)
        {
            MemoryStream outputMemStream = new MemoryStream();
            var          zipStream       = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outputMemStream);

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

            var newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryName);

            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(memStreamIn, zipStream, new byte[4096]);
            zipStream.CloseEntry();

            zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream.
            zipStream.Close();               // Must finish the ZipOutputStream before using outputMemStream.

            outputMemStream.Position = 0;
            return(outputMemStream);

            // Alternative outputs:
            // ToArray is the cleaner and easiest to use correctly with the penalty of duplicating allocated memory.

            //byte[] byteArrayOut = outputMemStream.ToArray();

            // GetBuffer returns a raw buffer raw and so you need to account for the true length yourself.
            //byte[] byteArrayOut = outputMemStream.GetBuffer();
            //long len = outputMemStream.Length;
        }
Пример #3
0
        public void ZIP(string SourcePath, string DestFile, int Compression, bool Subdir)
        {
            string[] fileList = GetFileList(SourcePath, Subdir);

            if (!Directory.Exists(Path.GetDirectoryName(DestFile)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(DestFile));
            }
            FileStream fs = File.Create(DestFile);

            ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fs);
            s.SetLevel(Compression);
            foreach (string fileName in fileList)
            {
                FileStream fs2 = File.OpenRead(fileName);

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

                ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);

                s.PutNextEntry(entry);

                s.Write(buffer, 0, buffer.Length);
            }
            s.Finish();
            s.Close();
        }
Пример #4
0
        /// <summary>
        /// Zip và tải xuống file nén các file
        /// </summary>
        /// <param name="serial"></param>
        /// <param name="listFiles"></param>
        /// <param name="path"></param>
        /// <param name="response"></param>
        public void DownloadMultiFiles(string serial, List <string> listFiles, string path, HttpResponse response)
        {
            string fullName    = "";
            string zipName     = serial + ".zip";
            string zipFullPath = path + zipName;

            ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOut =
                new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(zipFullPath));
            foreach (string fileName in listFiles)
            {
                fullName = path + "\\" + fileName;
                System.IO.FileInfo fi = new System.IO.FileInfo(fullName);
                ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fi.Name);
                System.IO.FileStream sReader = System.IO.File.OpenRead(fullName);
                byte[] buff = new byte[Convert.ToInt32(sReader.Length)];
                sReader.Read(buff, 0, (int)sReader.Length);
                entry.DateTime = fi.LastWriteTime;
                entry.Size     = sReader.Length;
                sReader.Close();
                zipOut.PutNextEntry(entry);
                zipOut.Write(buff, 0, buff.Length);
            }
            zipOut.Finish();
            zipOut.Close();
            DownloadSingleFile(zipName, zipFullPath, response);
        }
Пример #5
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;
        }
Пример #6
0
        public static void Compress(Stream data, Stream outData, string fileName)
        {
            string str = "";

            try
            {
                using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outData))
                {
                    zipStream.SetLevel(3);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
                    newEntry.DateTime = DateTime.UtcNow;
                    zipStream.PutNextEntry(newEntry);
                    data.Position = 0;
                    int    size   = (data.CanSeek) ? Math.Min((int)(data.Length - data.Position), 0x2000) : 0x2000;
                    byte[] buffer = new byte[size];
                    int    n;
                    do
                    {
                        n = data.Read(buffer, 0, buffer.Length);
                        zipStream.Write(buffer, 0, n);
                    } while (n != 0);
                    zipStream.CloseEntry();
                    zipStream.Flush();
                    zipStream.Close();
                }
            }
            catch (Exception ex)
            {
                str = ex.Message;
            }
        }
        /// <summary>
        /// Exports the query results to an excel file per query.
        /// </summary>
        /// <param name="viewType">Indicates the type of response view.</param>
        /// <returns></returns>
        public Stream ExportAsExcel(TaskItemTypes viewType)
        {
            MemoryStream ms = new MemoryStream();
            var          includeDataMartName = viewType != TaskItemTypes.AggregateResponse;

            if (Queries.Count() > 1)
            {
                var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms);
                zipStream.IsStreamOwner = false;

                foreach (var grouping in Queries)
                {
                    var    datamartAcronym  = includeDataMartName ? "-" + grouping.Select(g => g.DataMartAcronym).FirstOrDefault() : string.Empty;
                    string zipEntryFilename = Path.ChangeExtension(CleanFilename(grouping.Key.QueryName + datamartAcronym), "xlsx");

                    var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryFilename);
                    zipEntry.DateTime = DateTime.Now;
                    zipStream.PutNextEntry(zipEntry);

                    WriteExcel(zipStream, grouping.AsEnumerable(), includeDataMartName);
                    zipStream.CloseEntry();
                }

                zipStream.Close();
            }
            else
            {
                WriteExcel(ms, Queries.ElementAt(0).ToArray(), includeDataMartName);
            }

            ms.Position = 0;

            return(ms);
        }
Пример #8
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)))
                {
                    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);
        }
Пример #9
0
        bool Zip()
        {
            var xapName = XapFilename.ItemSpec;

            if (File.Exists(xapName))
            {
                DateTime lastMod    = File.GetLastWriteTime(xapName);
                bool     needsWrite = false;
                foreach (ITaskItem file_item in InputFiles)
                {
                    if (File.GetLastWriteTime(file_item.ItemSpec) > lastMod)
                    {
                        needsWrite = true;
                        break;
                    }
                }
                if (!needsWrite)
                {
                    Log.LogMessage(MessageImportance.Low, "Skipping xap file {0} generation, its up-to date");
                    return(true);
                }
            }

            Log.LogMessage(MessageImportance.Normal, "Generating compressed xap file {0}", xapName);
            try
            {
                using (FileStream fs = new FileStream(xapName, FileMode.Create))
                {
                    var zip_stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fs);
                    zip_stream.SetLevel(9);

                    AddFilesToZip(InputFiles, zip_stream);
                    AddFilesToZip(LocalCopyReferences, zip_stream);

                    zip_stream.Finish();
                    zip_stream.Close();
                }
            }
            catch (IOException ex)
            {
                Log.LogError("Error writing xap file.", ex);
                Log.LogMessage(MessageImportance.Low, "Error writing xap file:" + ex.ToString());

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

                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Exports the responses in csv format, if the response is multi-query each query response will be a separate csv file zipped into a file of the request name.
        /// </summary>
        /// <param name="viewType">The response result view type, Individual or Aggregate.</param>
        /// <returns></returns>
        public Stream ExportAsCSV(TaskItemTypes viewType)
        {
            var queries             = Queries.ToArray();
            var includeDataMartName = viewType != TaskItemTypes.AggregateResponse;

            MemoryStream ms = new MemoryStream();

            if (queries.Count() > 1)
            {
                var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms);
                zipStream.IsStreamOwner = false;

                foreach (var grouping in Queries)
                {
                    var    datamartAcronym  = includeDataMartName ? "-" + grouping.Select(g => g.DataMartAcronym).FirstOrDefault() : string.Empty;
                    string zipEntryFilename = Path.ChangeExtension(CleanFilename(grouping.Key.QueryName + datamartAcronym), "csv");

                    var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryFilename);
                    zipEntry.DateTime = DateTime.Now;
                    zipStream.PutNextEntry(zipEntry);

                    using (var writer = new StreamWriter(zipStream, System.Text.Encoding.Default, 1024, true))
                    {
                        for (int i = 0; i < grouping.Count(); i++)
                        {
                            var responseResult = grouping.ElementAt(i);
                            WriteCSV(writer, responseResult, i == 0, includeDataMartName);
                        }

                        writer.Flush();
                        zipStream.CloseEntry();
                    }
                }

                zipStream.Close();
            }
            else
            {
                var firstQueryGrouping = Queries.ElementAt(0).ToArray();
                using (var writer = new StreamWriter(ms, System.Text.Encoding.Default, 1024, true))
                {
                    for (int i = 0; i < firstQueryGrouping.Length; i++)
                    {
                        WriteCSV(writer, firstQueryGrouping[i], i == 0, includeDataMartName);
                    }
                    writer.Flush();
                }
            }

            ms.Position = 0;
            return(ms);
        }
Пример #11
0
        /// <summary>
        /// 压缩文件,只支持zip压缩
        /// </summary>
        /// <param name="fileAbsolutePathList">文件绝对路径的列表</param>
        /// <param name="compressFileName">压缩后文件的名称</param>
        /// <param name="isCoverOrNew">true为覆盖,false为新建</param>
        /// <returns></returns>
        public static string CompressFiles(List <string> fileAbsolutePathList, List <string> fileNameList, string compressFileName, bool isCoverOrNew)
        {
            if (fileAbsolutePathList == null || fileAbsolutePathList.Count < 1)
            {
                throw new Exception("至少传入一个文件或文件夹的绝对路径!");
            }
            string firstPath = fileAbsolutePathList[0].Replace('/', '\\');
            string dirPath   = firstPath.Substring(0, firstPath.LastIndexOf('\\') + 1);

            if (string.IsNullOrEmpty(compressFileName))
            {
                compressFileName = firstPath.Substring(firstPath.LastIndexOf('\\'));//取出最后一个\后面的字符串 作为文件名
                if (System.IO.File.Exists(firstPath))
                {
                    compressFileName = compressFileName.Substring(0, compressFileName.LastIndexOf('.'));//去除文件名的扩展名
                }
            }
            if (!Path.IsPathRooted(compressFileName))
            {
                compressFileName = GetNewFilePath(dirPath, compressFileName + ".zip", isCoverOrNew);                                                                    //获取合法的文件名
            }
            ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutput = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(new FileStream(compressFileName, FileMode.Create)); //新建压缩文件流 “ZipOutputStream”
            try
            {
                zipOutput.SetLevel(9); //压缩等级
                for (int i = 0; i < fileAbsolutePathList.Count; i++)
                {
                    if (fileNameList == null || fileNameList.Count != fileAbsolutePathList.Count)
                    {
                        appendStream(zipOutput, fileAbsolutePathList[i], dirPath);
                    }
                    else
                    {
                        appendStream(zipOutput, fileAbsolutePathList[i], fileNameList[i], dirPath);
                    }
                }
                zipOutput.Finish();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                zipOutput.Close();
                zipOutput.Dispose();
            }

            return(compressFileName);
        }
Пример #12
0
        public static MemoryStream CompressStream(MemoryStream stream, string entryname)
        {
            MemoryStream ms = new MemoryStream();

            using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipstream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms))
            {
                ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(entryname);
                entry.DateTime = DateTime.Now;
                zipstream.PutNextEntry(entry);
                zipstream.Write(stream.ToArray(), 0, (int)stream.Length);
                zipstream.Flush();
                zipstream.Finish();
                zipstream.Close();
            }
            return(ms);
        }
Пример #13
0
        public static void ZipFile(System.Collections.Generic.List <string> filesToZip, string outFile, int compression = 3, bool IsMapPath = true)
        {
            outFile = IsMapPath ? TM.Core.IO.MapPath(outFile) : outFile;
            if (compression < 0 || compression > 9)
            {
                throw new ArgumentException("Invalid compression rate (just 0-9).");
            }

            if (!Directory.Exists(new FileInfo(outFile).Directory.ToString()))
            {
                throw new ArgumentException("The Path does not exist.");
            }

            foreach (string c in filesToZip)
            {
                if (!File.Exists(IsMapPath ? TM.Core.IO.MapPath(c) : c))
                {
                    throw new ArgumentException(string.Format("The File {0} does not exist!", c));
                }
            }

            var crc32  = new ICSharpCode.SharpZipLib.Checksum.Crc32();
            var stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(outFile));

            stream.SetLevel(compression);

            for (int i = 0; i < filesToZip.Count; i++)
            {
                var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filesToZip[i]));
                entry.DateTime = DateTime.Now;
                var _filesToZip = IsMapPath ? TM.Core.IO.MapPath(filesToZip[i]) : filesToZip[i];
                using (FileStream fs = File.OpenRead(_filesToZip))
                {
                    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();
        }
Пример #14
0
        private void Compress(Stream data, Stream outData)
        {
            string str = "";

            try
            {
                using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outData))
                {
                    zipStream.SetLevel(3);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("data.xml");
                    newEntry.DateTime = DateTime.UtcNow;
                    //newEntry.Size = data.Length;
                    zipStream.PutNextEntry(newEntry);

                    //data.CopyTo(zipStream);
                    //CopyStream(data, zipStream);
                    //zipStream.Write(data, 0, data.Length);
                    // zipStream.Finish();
                    //zipStream.Close();//?

                    //byte[] buffer = new byte[32768];
                    //int read;
                    //while ((read = data.Read(buffer, 0, buffer.Length)) > 0)
                    //{
                    //    zipStream.Write(buffer, 0, read);
                    //}

                    data.Position = 0;
                    int    size   = (data.CanSeek) ? Math.Min((int)(data.Length - data.Position), 0x2000) : 0x2000;
                    byte[] buffer = new byte[size];
                    int    n;
                    do
                    {
                        n = data.Read(buffer, 0, buffer.Length);
                        zipStream.Write(buffer, 0, n);
                    } while (n != 0);
                    zipStream.CloseEntry();
                    zipStream.Flush();
                    zipStream.Close();
                }
            }
            catch (Exception ex)
            {
                str = ex.Message;
            }
        }
Пример #15
0
 /// <summary>
 ///  压缩多个文件
 /// </summary>
 /// <param name="files">文件名</param>
 /// <param name="ZipedFileName">压缩包文件名</param>
 /// <param name="Password">解压码</param>
 /// <returns></returns>
 public static void Zip(string[] files, string ZipedFileName, string Password)
 {
     files = files.Where(f => System.IO.File.Exists(f) || System.IO.Directory.Exists(f)).ToArray();
     if (files.Length == 0)
     {
         throw new System.IO.FileNotFoundException("未找到指定打包的文件");
     }
     ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(ZipedFileName));
     s.SetLevel(6);
     if (!string.IsNullOrEmpty(Password.Trim()))
     {
         s.Password = Password.Trim();
     }
     Zip(files, s);
     s.Finish();
     s.Close();
 }
Пример #16
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();
        }
Пример #17
0
		bool Zip ()
		{
			var xapName = XapFilename.ItemSpec;
			if (File.Exists (xapName)) {
				DateTime lastMod = File.GetLastWriteTime (xapName);
				bool needsWrite = false;
				foreach (ITaskItem file_item in InputFiles) {
					if (File.GetLastWriteTime (file_item.ItemSpec) > lastMod) {
						needsWrite = true;
						break;
					}
				}
				if (!needsWrite) {
					Log.LogMessage (MessageImportance.Low, "Skipping xap file {0} generation, its up-to date");
					return true;
				}
			}

			Log.LogMessage (MessageImportance.Normal, "Generating compressed xap file {0}", xapName);
			try {
				using (FileStream fs = new FileStream (xapName, FileMode.Create)) {
					var zip_stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream (fs);
					zip_stream.SetLevel (9);

					AddFilesToZip (InputFiles, zip_stream);
					AddFilesToZip (LocalCopyReferences, zip_stream);

					zip_stream.Finish ();
					zip_stream.Close ();
				}
			} catch (IOException ex) {
				Log.LogError ("Error writing xap file.", ex);
				Log.LogMessage (MessageImportance.Low, "Error writing xap file:" + ex.ToString ());

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

				return false;
			}

			return true;
		}
Пример #18
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());
     }
 }
Пример #19
0
        public static void CreateSample(string outPathname, string password, string folderName)
        {
            FileStream fsOut     = File.Create(outPathname);
            var        zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut);

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

            zipStream.Password = password; // optional. Null is the same as not setting. Required if using AES.

            // This setting will strip the leading part of the folder path in the entries, to
            // make the entries relative to the starting folder.
            // To include the full path for each entry up to the drive root, assign folderOffset = 0.
            int folderOffset = folderName.Length + (folderName.EndsWith("\\") ? 0 : 1);

            CompressFolder(folderName, zipStream, folderOffset);

            zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream
            zipStream.Close();
        }
Пример #20
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;
        }
        protected virtual void SerializeHeightmap(Map map, Stream stream)
        {
            // Heightmap serialization method 3
            var i     = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream);
            var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Heightmap");

            i.PutNextEntry(entry);
            var bw = new BinaryWriter(i);

            bw.Write(map.Ground.Heightmap.GetLength(0));
            bw.Write(map.Ground.Heightmap.GetLength(1));
            for (var y = 0; y < map.Ground.Heightmap.GetLength(0); y++)
            {
                for (var x = 0; x < map.Ground.Heightmap.GetLength(1); x++)
                {
                    bw.Write(map.Ground.Heightmap[y, x].R);
                }
            }
            i.Close();
        }
Пример #22
0
        public static byte[] CompressFile(byte[] data, string filename)
        {
            Stream stream = new MemoryStream(data);

            // 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;
                    zipStream.PutNextEntry(newEntry);
                    StreamUtils.Copy(stream, zipStream, new byte[2048]);
                    zipStream.Finish();
                    zipStream.Close();
                }
                return(fsOut.ToArray());
            }
        }
Пример #23
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);
        }
Пример #24
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);
        }
Пример #25
0
        private byte[] CompressFile(byte[] data)
        {
            Stream stream = new MemoryStream(data);

            // 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("data.xml");
                    newEntry.DateTime = DateTime.UtcNow;
                    zipStream.PutNextEntry(newEntry);
                    //zipStream.Write(data, 0, data.Length);
                    StreamUtils.Copy(stream, zipStream, new byte[2048]);
                    zipStream.Finish();
                    zipStream.Close();
                }
                return(fsOut.ToArray());
            }
        }
Пример #26
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);
            }
        }
Пример #27
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);
        }
        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());
                    }
                }
            }
        }
Пример #29
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;
        }
Пример #30
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;
        }
Пример #31
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);
        }
Пример #32
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;
     }
 }
Пример #33
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();
     }
 }
Пример #34
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);
        }
Пример #35
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
Пример #36
0
		public static void InternalSaveMiniProject(IStorage pStgSave, AltaxoDocument projectToSave, string graphDocumentName)
		{
			ComDebug.ReportInfo("GraphDocumentDataObject.InternalSaveMiniProject BEGIN");

			try
			{
				Exception saveEx = null;
				Ole32Func.WriteClassStg(pStgSave, typeof(GraphDocumentEmbeddedComObject).GUID);

				// Store the version of this assembly
				{
					var assembly = System.Reflection.Assembly.GetExecutingAssembly();
					Version version = assembly.GetName().Version;
					using (var stream = new ComStreamWrapper(pStgSave.CreateStream("AltaxoVersion", (int)(STGM.DIRECT | STGM.READWRITE | STGM.CREATE | STGM.SHARE_EXCLUSIVE), 0, 0), true))
					{
						string text = version.ToString();
						byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(text);
						stream.Write(nameBytes, 0, nameBytes.Length);
					}
				}

				// Store the name of the item
				using (var stream = new ComStreamWrapper(pStgSave.CreateStream("AltaxoGraphName", (int)(STGM.DIRECT | STGM.READWRITE | STGM.CREATE | STGM.SHARE_EXCLUSIVE), 0, 0), true))
				{
					byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(graphDocumentName);
					stream.Write(nameBytes, 0, nameBytes.Length);
				}

				// Store the project
				using (var stream = new ComStreamWrapper(pStgSave.CreateStream("AltaxoProjectZip", (int)(STGM.DIRECT | STGM.READWRITE | STGM.CREATE | STGM.SHARE_EXCLUSIVE), 0, 0), true))
				{
					using (var zippedStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream))
					{
						var zippedStreamWrapper = new Altaxo.Main.ZipOutputStreamWrapper(zippedStream);
						var info = new Altaxo.Serialization.Xml.XmlStreamSerializationInfo();
						projectToSave.SaveToZippedFile(zippedStreamWrapper, info);
						zippedStream.Close();
					}
					stream.Close();
				}

				if (null != saveEx)
					throw saveEx;
			}
			catch (Exception ex)
			{
				ComDebug.ReportError("InternalSaveMiniProject, Exception ", ex);
			}
			finally
			{
				Marshal.ReleaseComObject(pStgSave);
			}

			ComDebug.ReportInfo("GraphDocumentDataObject.InternalSaveMiniProject END");
		}
        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());
                    }
                }
            }
        }
Пример #38
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();
        }
 protected virtual void SerializeHeightmap(Map map, Stream stream)
 {
     // Heightmap serialization method 3
     var i = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream);
     var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Heightmap");
     i.PutNextEntry(entry);
     var bw = new BinaryWriter(i);
     bw.Write(map.Ground.Heightmap.GetLength(0));
     bw.Write(map.Ground.Heightmap.GetLength(1));
     for (var y = 0; y < map.Ground.Heightmap.GetLength(0); y++)
         for (var x = 0; x < map.Ground.Heightmap.GetLength(1); x++)
             bw.Write(map.Ground.Heightmap[y, x].R);
     i.Close();
 }
		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;
		}