SetComment() 공개 메소드

Set the zip file comment.
/// The converted comment is longer than 0xffff bytes. ///
public SetComment ( string comment ) : void
comment string /// The comment text for the entire archive. ///
리턴 void
예제 #1
0
        public void CommentTooLong()
        {
            MemoryStream    ms = new MemoryStream();
            ZipOutputStream s  = new ZipOutputStream(ms);

            s.SetComment(new String('A', 65536));
        }
        /// <summary>
        /// 压缩多个文件/文件夹
        /// </summary>
        /// <param name="comment">注释信息</param>
        /// <param name="password">压缩密码</param>
        /// <param name="compressionLevel">压缩等级,范围从0到9,可选,默认为6</param>
        /// <param name="filePaths">压缩文件路径</param>
        /// <returns></returns>
        private MemoryStream CreateZip(string comment, string password, int compressionLevel, params string[] filePaths)
        {
            MemoryStream memoryStream = new MemoryStream();

            using (SharpZipLib.ZipOutputStream zipStream = new SharpZipLib.ZipOutputStream(memoryStream))
            {
                if (!string.IsNullOrWhiteSpace(password))
                {
                    zipStream.Password = password;//设置密码
                }

                if (!string.IsNullOrWhiteSpace(comment))
                {
                    zipStream.SetComment(comment);//添加注释
                }

                //设置压缩级别
                zipStream.SetLevel(compressionLevel);

                foreach (string item in filePaths)//从字典取文件添加到压缩文件
                {
                    //如果不是文件直接跳过不打包
                    if (!File.Exists(item))
                    {
                        continue;
                    }

                    FileInfo fileInfo = new FileInfo(item);

                    using (FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        SharpZipLib.ZipEntry zipEntry = new SharpZipLib.ZipEntry(Path.GetFileName(item));

                        zipEntry.DateTime = fileInfo.LastWriteTime;

                        zipEntry.Size = fileStream.Length;

                        zipStream.PutNextEntry(zipEntry);

                        int readLength = 0;

                        byte[] buffer = new byte[bufferSize];

                        do
                        {
                            readLength = fileStream.Read(buffer, 0, bufferSize);
                            zipStream.Write(buffer, 0, readLength);
                        }while (readLength == bufferSize);
                    }
                }
            }

            return(memoryStream);
        }
예제 #3
0
 void MakeZipFile(string name, string entryNamePrefix, int entries, int size, string comment)
 {
     using (FileStream fs = File.Create(name)) {
         ZipOutputStream zOut = new ZipOutputStream(fs);
         zOut.SetComment(comment);
         for (int i = 0; i < entries; ++i)
         {
             zOut.PutNextEntry(new ZipEntry(entryNamePrefix + (i + 1).ToString()));
             AddKnownDataToEntry(zOut, size);
         }
         zOut.Close();
         fs.Close();
     }
 }
예제 #4
0
 void MakeZipFile(string name, string[] names, int size, string comment)
 {
     using (FileStream fs = File.Create(name)) {
         ZipOutputStream zOut = new ZipOutputStream(fs);
         zOut.SetComment(comment);
         for (int i = 0; i < names.Length; ++i)
         {
             zOut.PutNextEntry(new ZipEntry(names[i]));
             AddKnownDataToEntry(zOut, size);
         }
         zOut.Close();
         fs.Close();
     }
 }
예제 #5
0
		private void WriteResources()
		{
			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;

			for (int i = 0; i < options.jars.Count; i++)
			{
				bool hasEntries = false;
				MemoryStream mem = new MemoryStream();
				using (ZipOutputStream zip = new ZipOutputStream(mem))
				{
					if (!string.IsNullOrEmpty(options.jars[i].Comment))
					{
						zip.SetComment(options.jars[i].Comment);
					}
					zip.SetLevel(9);
					List<string> stubs = new List<string>();
					foreach (Jar.Item item in options.jars[i])
					{
						if (item.IsStub)
						{
							// we don't want stub class pseudo resources for classes loaded from the file system
							if (i != options.classesJar)
							{
								stubs.Add(item.Name);
							}
							continue;
						}
						ZipEntry zipEntry = item.ZipEntry;
						if (options.compressedResources || zipEntry.CompressionMethod != CompressionMethod.Stored)
						{
							zipEntry.CompressionMethod = CompressionMethod.Deflated;
						}
						zip.PutNextEntry(zipEntry);
						byte[] data = item.GetData();
						zip.Write(data, 0, data.Length);
						zip.CloseEntry();
						hasEntries = true;
					}
					if (stubs.Count != 0)
					{
						// generate the --ikvm-classes-- file in the jar
						ZipEntry zipEntry = new ZipEntry(JVM.JarClassList);
						zipEntry.CompressionMethod = CompressionMethod.Deflated;
						zip.PutNextEntry(zipEntry);
						BinaryWriter bw = new BinaryWriter(zip);
						bw.Write(stubs.Count);
						foreach (string classFile in stubs)
						{
							bw.Write(classFile);
						}
						bw.Flush();
						zip.CloseEntry();
						hasEntries = true;
					}
				}
				// don't include empty classes.jar
				if (i != options.classesJar || hasEntries)
				{
					mem = new MemoryStream(mem.ToArray());
					string name = options.jars[i].Name;
					if (options.targetIsModule)
					{
						name = Path.GetFileNameWithoutExtension(name) + "-" + moduleBuilder.ModuleVersionId.ToString("N") + Path.GetExtension(name);
					}
					jarList.Add(name);
					moduleBuilder.DefineManifestResource(name, mem, ResourceAttributes.Public);
				}
			}
		}
예제 #6
0
        public string GetArchiveFilename(string path, string newline, out string referenceName)
        {
            var commit = GetCommitByPath(ref path, out referenceName);
            if (commit == null)
                return null;

            if (referenceName == null)
                referenceName = commit.Sha;

            var key = "archive";
            if (newline != null)
                key += newline.GetHashCode().ToString("x");
            bool exist;
            var filename = GitCache.GetCacheFilename(commit.Sha, key, out exist, true);
            if (exist)
                return filename;

            using (var zipOutputStream = new ZipOutputStream(new FileStream(filename, FileMode.Create)))
            {
                var stack = new Stack<Tree>();

                stack.Push(commit.Tree);
                while (stack.Count != 0)
                {
                    var tree = stack.Pop();
                    foreach (var entry in tree)
                    {
                        byte[] bytes;
                        switch (entry.TargetType)
                        {
                            case TreeEntryTargetType.Blob:
                                zipOutputStream.PutNextEntry(new ZipEntry(entry.Path));
                                var blob = (Blob)entry.Target;
                                bytes = blob.GetContentStream().ToBytes();
                                if (newline == null)
                                    zipOutputStream.Write(bytes, 0, bytes.Length);
                                else
                                {
                                    var encoding = FileHelper.DetectEncoding(bytes, CpToEncoding(commit.Encoding), _i18n.Value);
                                    if (encoding == null)
                                        zipOutputStream.Write(bytes, 0, bytes.Length);
                                    else
                                    {
                                        bytes = FileHelper.ReplaceNewline(bytes, encoding, newline);
                                        zipOutputStream.Write(bytes, 0, bytes.Length);
                                    }
                                }
                                break;
                            case TreeEntryTargetType.Tree:
                                stack.Push((Tree)entry.Target);
                                break;
                            case TreeEntryTargetType.GitLink:
                                zipOutputStream.PutNextEntry(new ZipEntry(entry.Path + "/.gitsubmodule"));
                                bytes = Encoding.ASCII.GetBytes(entry.Target.Sha);
                                zipOutputStream.Write(bytes, 0, bytes.Length);
                                break;
                        }
                    }
                }
                zipOutputStream.SetComment(commit.Sha);
            }

            return filename;
        }
예제 #7
0
 protected void MakeZipFile(string name, string entryNamePrefix, int entries, int size, string comment)
 {
     using (var store = IsolatedStorageFile.GetUserStoreForApplication())
     {
         using (IsolatedStorageFileStream fs = store.CreateFile(name))
         {
             using (ZipOutputStream zOut = new ZipOutputStream(fs))
             {
                 zOut.SetComment(comment);
                 for (int i = 0; i < entries; ++i)
                 {
                     zOut.PutNextEntry(new ZipEntry(entryNamePrefix + (i + 1).ToString()));
                     AddKnownDataToEntry(zOut, size);
                 }
             }
         }
     }
 }
예제 #8
0
 protected void MakeZipFile(string name, string[] names, int size, string comment)
 {
     using (var store = IsolatedStorageFile.GetUserStoreForApplication())
     {
         using (IsolatedStorageFileStream fs = store.CreateFile(name))
         {
             using (ZipOutputStream zOut = new ZipOutputStream(fs))
             {
                 zOut.SetComment(comment);
                 for (int i = 0; i < names.Length; ++i)
                 {
                     zOut.PutNextEntry(new ZipEntry(names[i]));
                     AddKnownDataToEntry(zOut, size);
                 }
                 zOut.Close();
             }
             fs.Close();
         }
     }
 }
예제 #9
0
        public void SetCommentOversize()
        {
            var ms = new MemoryStream();
            var s = new ZipOutputStream(ms);
            //s.SetComment(new String('A', 65536));

            Assert.That(() => s.SetComment(new String('A', 65536)),
                Throws.TypeOf<ArgumentOutOfRangeException>());
        }
예제 #10
0
 public void SetCommentOversize()
 {
     MemoryStream ms = new MemoryStream();
     ZipOutputStream s = new ZipOutputStream(ms);
     s.SetComment(new String('A', 65536));
 }
예제 #11
0
 protected void MakeZipFile(string name, string entryNamePrefix, int entries, int size, string comment)
 {
     using (FileStream fs = File.Create(name))
     using (ZipOutputStream zOut = new ZipOutputStream(fs)) {
         zOut.SetComment(comment);
         for (int i = 0; i < entries; ++i) {
             zOut.PutNextEntry(new ZipEntry(entryNamePrefix + (i + 1).ToString()));
             AddKnownDataToEntry(zOut, size);
         }
     }
 }
예제 #12
0
        private void ZipDirectory(string zipfile, string folder, string comment, List<KeyValuePair<string, string>> filemap)
        {
            ICSharpCode.SharpZipLib.Zip.ZipConstants.DefaultCodePage = System.Text.Encoding.UTF8.CodePage;
            ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
            using (System.IO.FileStream ofs = new System.IO.FileStream(zipfile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
            using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ofs))
            {
                try
                {
                    zip.SetLevel(9);
                    if (!string.IsNullOrEmpty(comment))
                        zip.SetComment(comment);

                    int i = 0;

                    foreach (KeyValuePair<string, string> f in filemap)
                    {
                        if (Progress != null)
                            Progress(ProgressType.Compressing, f.Key, filemap.Count, i);

                        System.IO.FileInfo fi = new System.IO.FileInfo(f.Value);
                        ICSharpCode.SharpZipLib.Zip.ZipEntry ze = new ICSharpCode.SharpZipLib.Zip.ZipEntry(RelativeName(f.Key, folder).Replace('\\', '/'));
                        ze.DateTime = fi.LastWriteTime;
                        ze.Size = fi.Length;
                        zip.PutNextEntry(ze);
                        using (System.IO.FileStream fs = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
                            Utility.CopyStream(fs, zip);

                        if (Progress != null)
                            Progress(ProgressType.Compressing, f.Key, filemap.Count, i++);
                    }

                    zip.Finish();
                }
                finally
                {
                    try { zip.Close(); }
                    catch { }
                }
            }
        }
예제 #13
0
파일: Zip.cs 프로젝트: xsharper/xsharper
        private object createZip(Stream fileStream, string sourceDirectory, IStringFilter nf, IStringFilter df)
        {
            ZipEntryFactory entryFactory;
            switch (ZipTime)
            {
                default:
                case ZipTime.Now:
                    entryFactory = new ZipEntryFactory(DateTime.Now);
                    break;
                case ZipTime.UtcNow:
                    entryFactory = new ZipEntryFactory(DateTime.UtcNow);
                    break;
                case ZipTime.FileTime:
                    entryFactory = new ZipEntryFactory(ZipEntryFactory.TimeSetting.LastWriteTime);
                    break;
                case ZipTime.UtcFileTime:
                    entryFactory = new ZipEntryFactory(ZipEntryFactory.TimeSetting.LastWriteTimeUtc);
                    break;
            }
            entryFactory.NameTransform = new ZipNameTransform(sourceDirectory);
            entryFactory.IsUnicodeText = Unicode;

            ProgressHandler progress = delegate(object x, ProgressEventArgs y) { Context.OnProgress(1, y.Name); };
            using (ZipOutputStream zip = new ZipOutputStream(fileStream))
            {
                if (Comment!=null)
                    zip.SetComment(Context.TransformStr(Password, Transform));
                if (Password != null)
                    zip.Password = Context.TransformStr(Password, Transform);
                zip.SetLevel(Level);

                return scanDir(sourceDirectory, new scanDirParams(zip, sourceDirectory, entryFactory, progress, nf, df));
            }
        }
예제 #14
0
        public static void SignPackage(Stream input, X509Certificate2 certificate, Stream output, bool signWholeFile)
        {
            JarFile inputJar = null;
            ZipOutputStream outputJar = null;

            // Assume the certificate is valid for at least an hour.
            DateTime timestamp = DateTime.Parse(certificate.GetEffectiveDateString()).AddHours(1);

            inputJar = new JarFile(input);  // Don't verify.

            Stream outputStream = null;
            if (signWholeFile)
            {
                outputStream = new MemoryStream();
            }
            else
            {
                outputStream = output;
            }
            outputJar = new ZipOutputStream(outputStream);
            outputJar.SetComment(null);
            outputJar.SetLevel(9);

            JarEntry je;

            Manifest manifest = addDigestsToManifest(inputJar);

            // Everything else
            copyFiles(manifest, inputJar, outputJar, timestamp);

            // otacert
            if (signWholeFile)
            {
                addOtacert(outputJar, certificate, timestamp, manifest);
            }

            var buffer = new MemoryStream();

            // MANIFEST.MF
            je = new JarEntry(JarFile.MANIFEST_NAME);
            je.DateTime = timestamp;
            manifest.Write(buffer);
            je.Size = buffer.Length;
            outputJar.PutNextEntry(je);
            buffer.WriteTo(outputJar);

            // CERT.SF
            var signature = new MemoryStream();
            je = new JarEntry(CERT_SF_NAME);
            je.DateTime = timestamp;
            buffer.SetLength(0);
            writeSignatureFile(manifest, signature);
            signature.WriteTo(buffer);
            je.Size = buffer.Length;
            outputJar.PutNextEntry(je);
            buffer.WriteTo(outputJar);

            // CERT.RSA
            je = new JarEntry(CERT_RSA_NAME);
            je.DateTime = timestamp;
            buffer.SetLength(0);
            writeSignatureBlock(signature, certificate, buffer);
            je.Size = buffer.Length;
            outputJar.PutNextEntry(je);
            buffer.WriteTo(outputJar);

            outputJar.Close();
            outputJar = null;

            if (signWholeFile)
            {
                signWholeOutputFile(((MemoryStream)outputStream).ToArray(),
                                    output, certificate);
            }
        }
예제 #15
0
    private void SaveBackground_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            string tmpdirectorypath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "tmp") + System.IO.Path.DirectorySeparatorChar;

            using (FileStream tempFileStream = new FileStream(ProjectSavePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
            {
                using (ZipOutputStream zipOutput = new ZipOutputStream(tempFileStream))
                {
                    // Zip with highest compression.
                    zipOutput.SetLevel(9);
                    zipOutput.SetComment(ProjectInfo.FileVersion.ToString());

                    //Project Data
                    string projfilename = SaveProject(tmpdirectorypath);
                    using (FileStream fileStream = new FileStream(projfilename, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // Read full stream to in-memory buffer.
                        byte[] buffer = new byte[fileStream.Length];
                        fileStream.Read(buffer, 0, buffer.Length);

                        // Create a new entry for the current file.
                        ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(projfilename));
                        entry.DateTime = DateTime.Now;
                        entry.Size = fileStream.Length;
                        entry.Comment = "Main";
                        fileStream.Close();
                        zipOutput.PutNextEntry(entry);
                        zipOutput.Write(buffer, 0, buffer.Length);
                        buffer = null;
                    }

                    //Thumbs
                    string[] thumbs = Directory.GetFiles(Thumbpath);
                    for (int i = 0; i < thumbs.Length; i++)
                    {
                        using (FileStream fileStream = new FileStream(thumbs[i], FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            // Read full stream to in-memory buffer.
                            byte[] buffer = new byte[fileStream.Length];
                            fileStream.Read(buffer, 0, buffer.Length);

                            // Create a new entry for the current file.
                            ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(thumbs[i]));
                            entry.DateTime = DateTime.Now;
                            entry.Size = fileStream.Length;
                            entry.Comment = "Thumb";
                            fileStream.Close();
                            zipOutput.PutNextEntry(entry);
                            zipOutput.Write(buffer, 0, buffer.Length);
                            buffer = null;
                        }
                    }

                    zipOutput.Finish();
                    zipOutput.Flush();
                    zipOutput.Close();
                }
            }

            Directory.Delete(tmpdirectorypath, true);

            ProjectSaved = true;
            e.Result = true;
        }
        catch (Exception ex)
        {
            e.Result = false;
            ThreadException = ex;
        }
    }
예제 #16
0
 protected void MakeZipFile(Stream storage, bool isOwner, string[] names, int size, string comment)
 {
     using (ZipOutputStream zOut = new ZipOutputStream(storage)) {
         zOut.IsStreamOwner = isOwner;
         zOut.SetComment(comment);
         for (int i = 0; i < names.Length; ++i) {
             zOut.PutNextEntry(new ZipEntry(names[i]));
             AddKnownDataToEntry(zOut, size);
         }
         zOut.Close();
     }
 }
예제 #17
0
 protected void MakeZipFile(string name, string[] names, int size, string comment)
 {
     using (FileStream fs = File.Create(name)) {
         using (ZipOutputStream zOut = new ZipOutputStream(fs)) {
             zOut.SetComment(comment);
             for (int i = 0; i < names.Length; ++i) {
                 zOut.PutNextEntry(new ZipEntry(names[i]));
                 AddKnownDataToEntry(zOut, size);
             }
             zOut.Close();
         }
         fs.Close();
     }
 }
예제 #18
0
 public void CommentTooLong()
 {
     MemoryStream ms = new MemoryStream();
     ZipOutputStream s = new ZipOutputStream(ms);
     s.SetComment(new String('A', 65536));
 }
예제 #19
0
 protected void MakeZipFile(Stream storage, bool isOwner,
     string entryNamePrefix, int entries, int size, string comment)
 {
     using (ZipOutputStream zOut = new ZipOutputStream(storage)) {
         zOut.IsStreamOwner = isOwner;
         zOut.SetComment(comment);
         for (int i = 0; i < entries; ++i) {
             zOut.PutNextEntry(new ZipEntry(entryNamePrefix + (i + 1).ToString()));
             AddKnownDataToEntry(zOut, size);
         }
     }
 }
예제 #20
0
파일: ZipTask.cs 프로젝트: RoastBoy/nant
        /// <summary>
        /// Creates the zip file.
        /// </summary>
        protected override void ExecuteTask() {
            ZipOutputStream zOutstream = null;
            
            Log(Level.Info, "Zipping {0} files to '{1}'.", 
                ZipFileSets.FileCount, ZipFile.FullName);
                
            try {
                if (!Directory.Exists(ZipFile.DirectoryName)) {
                    Directory.CreateDirectory(ZipFile.DirectoryName);
                }
            
                // set encoding to use for filenames and comment
                ZipConstants.DefaultCodePage = Encoding.CodePage;

                zOutstream = new ZipOutputStream(ZipFile.Create());

                // set compression level
                zOutstream.SetLevel(ZipLevel);

                // set comment
                if (!String.IsNullOrEmpty(Comment)) {
                    zOutstream.SetComment(Comment);
                }

                foreach (ZipFileSet fileset in ZipFileSets) {
                    string basePath = fileset.BaseDirectory.FullName;
                    if (Path.GetPathRoot(basePath) != basePath) {
                        basePath = Path.GetDirectoryName(basePath + Path.DirectorySeparatorChar);
                    }

                    // add files to zip
                    foreach (string file in fileset.FileNames) {
                        // ensure file exists (in case "asis" was used)
                        if (!File.Exists(file)) {
                            throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                "File '{0}' does not exist.", file), Location);
                        }

                        // the name of the zip entry
                        string entryName;

                        // determine name of the zip entry
                        if (!Flatten && file.StartsWith(basePath)) {
                            entryName = file.Substring(basePath.Length);
                            if (entryName.Length > 0 && entryName[0] == Path.DirectorySeparatorChar) {
                                entryName = entryName.Substring(1);
                            }

                            // remember that directory was added to zip file, so
                            // that we won't add it again later
                            string dir = Path.GetDirectoryName(file);
                            if (_addedDirs[dir] == null) {
                                _addedDirs[dir] = dir;
                            }
                        } else {
                            // flatten directory structure
                            entryName = Path.GetFileName(file);
                        }

                        // add prefix if specified
                        if (fileset.Prefix != null) {
                            entryName = fileset.Prefix + entryName;
                        }

                        // ensure directory separators are understood on linux
                        if (Path.DirectorySeparatorChar == '\\') {
                            entryName = entryName.Replace(@"\", "/");
                        }

                        // perform duplicate checking
                        if (_fileEntries.ContainsKey(entryName)) {
                            switch (DuplicateHandling) {
                                case DuplicateHandling.Add:
                                    break;
                                case DuplicateHandling.Fail:
                                    throw new BuildException(string.Format(
                                        CultureInfo.InvariantCulture, 
                                        "Duplicate file '{0}' was found.", 
                                        entryName), Location.UnknownLocation);
                                case DuplicateHandling.Preserve:
                                    // skip current entry
                                    continue;
                                default:
                                    throw new BuildException(string.Format(
                                        CultureInfo.InvariantCulture, 
                                        "Duplicate value '{0}' is not supported.", 
                                        DuplicateHandling.ToString()), 
                                        Location.UnknownLocation);
                            }
                        }

                        // create zip entry
                        ZipEntry entry = new ZipEntry(entryName);

                        // store entry (to allow for duplicate checking)
                        _fileEntries[entryName] = null;

                        // set date/time stamp on zip entry
                        if (Stamp != DateTime.MinValue) {
                            entry.DateTime = Stamp;
                        } else {
                            entry.DateTime = File.GetLastWriteTime(file);
                        }

                        // write file content to stream in small chuncks
                        using (FileStream fs = File.OpenRead(file)) {
                            // set size for backward compatibility with older unzip
                            entry.Size = fs.Length;

                            Log(Level.Verbose, "Adding {0}.", entryName);

                            // write file to zip file
                            zOutstream.PutNextEntry(entry);

                            byte[] buffer = new byte[50000];

                            while (true) {
                                int bytesRead = fs.Read(buffer, 0, buffer.Length);
                                if (bytesRead == 0)
                                    break;
                                zOutstream.Write(buffer, 0, bytesRead);
                            }
                        }

                    }

                    // add (possibly empty) directories to zip
                    if (IncludeEmptyDirs) {
                        foreach (string directory in fileset.DirectoryNames) {
                            // skip directories that were already added when the 
                            // files were added
                            if (_addedDirs[directory] != null) {
                                continue;
                            }

                            // skip directories that are not located beneath the base 
                            // directory
                            if (!directory.StartsWith(basePath) || directory.Length <= basePath.Length) {
                                continue;
                            }

                            // determine zip entry name
                            string entryName = directory.Substring(basePath.Length + 1);

                            // add prefix if specified
                            if (fileset.Prefix != null) {
                                entryName = fileset.Prefix + entryName;
                            }

                            // ensure directory separators are understood on linux
                            if (Path.DirectorySeparatorChar == '\\') {
                                entryName = entryName.Replace(@"\", "/");
                            }

                            if (!entryName.EndsWith("/")) {
                                // trailing directory signals to #ziplib that we're
                                // dealing with directory entry
                                entryName += "/";
                            }

                            // create directory entry
                            ZipEntry entry = new ZipEntry(entryName);

                            // set size for backward compatibility with older unzip
                            entry.Size = 0L;

                            // write directory to zip file
                            zOutstream.PutNextEntry(entry);
                        }
                    }
                }

                zOutstream.Close();
                zOutstream.Finish();
            } catch (Exception ex) {
                // close the zip output stream
                if (zOutstream != null) {
                    zOutstream.Close();
                }

                // delete the (possibly corrupt) zip file
                if (ZipFile.Exists) {
                    ZipFile.Delete();
                }

                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                    "Zip file '{0}' could not be created.", ZipFile.FullName), 
                    Location, ex);
            } finally {
                CleanUp();
            }
        }
예제 #21
0
        /// <summary>
        /// Packs the specified dictionary.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        /// <param name="archivePath">The archive path.</param>
        /// <returns>The full path (including the filename) to the archive or String.Empty of the process was interrupted.</returns>
        /// <remarks>Documented by Dev03, 2007-09-10</remarks>
        public string Pack(IDictionary dictionary, string archivePath)
        {
            string dictionaryPath = ((XML.XmlDictionary)dictionary).Path;
            string fullArchivePath = String.Empty;
            if ((Path.GetFileName(archivePath).Length == 0) || (Path.GetExtension(archivePath).Length == 0))
            {
                fullArchivePath = Path.Combine(archivePath, Path.GetRandomFileName() + Resources.DICTIONARY_ARCHIVE_EXTENSION);
            }
            else
            {
                fullArchivePath = archivePath;
            }

            FileStream target = File.Create(fullArchivePath);
            //ZipConstants.DefaultCodePage = Encoding.Unicode.CodePage;   //this may possibly mean that we are not Zip compatible anymore
            ZipOutputStream zip_stream = new ZipOutputStream(target);

            // set compression level 0(low) to 9 (high)
            zip_stream.SetLevel(5);
            // write the old category id to the header for backward compatibility
            zip_stream.SetComment(String.Format(Resources.PACKER_ARCHIVE_HEADER_COMMENT_PACK, dictionary.Category.OldId));

            string dirPath = Path.GetDirectoryName(dictionaryPath);
            Directory.SetCurrentDirectory(dirPath);
            List<string> resourceList = dictionary.GetResources();

            resourceList.Add(dictionaryPath);   //add the dictionary

            if (!ReportProgressUpdate(0)) return String.Empty;
            for (int i = 0; i < resourceList.Count; i++)
            {
                string fullPath, relPath;
                if (Path.IsPathRooted(resourceList[i]))
                {
                    if (resourceList[i].StartsWith(dirPath))
                    {
                        relPath = resourceList[i].Replace(dirPath, String.Empty).Trim(new char[] { Path.DirectorySeparatorChar, ' ' });
                        fullPath = resourceList[i];
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    try
                    {
                        relPath = resourceList[i];
                        fullPath = Path.GetFullPath(resourceList[i]);
                    }
                    catch
                    {
                        continue;
                    }
                }
                if (!File.Exists(fullPath))
                    continue;

                FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                // allocate file buffer
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);

                // writing zip entry and data
                ZipEntry entry = new ZipEntry(relPath);
                zip_stream.PutNextEntry(entry);
                zip_stream.Write(buffer, 0, buffer.Length);
                zip_stream.CloseEntry();
                fs.Close();

                int progress = (int)Math.Floor(100.0 * (i + 1) / resourceList.Count);
                if (!ReportProgressUpdate(progress)) return String.Empty;
            }
            if (!ReportProgressUpdate(100)) return String.Empty;

            zip_stream.Finish();
            zip_stream.Close();
            target.Close();
            return fullArchivePath;
        }
예제 #22
0
파일: Zip.cs 프로젝트: fugaku/scriptsharp
        private bool ZipFiles() {
            Crc32 crc = new Crc32();
            ZipOutputStream zs = null;

            try {
                string zipFileName = Path.GetFullPath(_zipFileName);
                string outputDirectory = Path.GetDirectoryName(zipFileName);

                string baseDirectory = null;
                if (String.IsNullOrEmpty(_workingDirectory) == false) {
                    baseDirectory = Path.GetFullPath(_workingDirectory);
                }

                if (Directory.Exists(outputDirectory) == false) {
                    Directory.CreateDirectory(outputDirectory);
                }

                Log.LogMessage("Creating zip file \"{0}\".", zipFileName);

                using (zs = new ZipOutputStream(File.Create(zipFileName))) {
                    // make sure level in range
                    _zipLevel = Math.Max(0, _zipLevel);
                    _zipLevel = Math.Min(9, _zipLevel);

                    zs.SetLevel(_zipLevel);
                    if (!String.IsNullOrEmpty(_comment)) {
                        zs.SetComment(_comment);
                    }

                    byte[] buffer = new byte[32768];

                    // add files to zip
                    foreach (ITaskItem fileItem in _files) {
                        string name = Path.GetFullPath(fileItem.ItemSpec);

                        FileInfo file = new FileInfo(name);
                        if (!file.Exists) {
                            Log.LogWarning("File Not Found: {0}.", file.FullName);
                            continue;
                        }

                        // clean up name
                        if (_flatten) {
                            name = file.Name;
                        }
                        else if (!String.IsNullOrEmpty(baseDirectory) &&
                                 name.StartsWith(baseDirectory, StringComparison.OrdinalIgnoreCase)) {
                            name = name.Substring(baseDirectory.Length);
                        }
                        name = ZipEntry.CleanName(name, true);

                        ZipEntry entry = new ZipEntry(name);
                        entry.DateTime = file.LastWriteTime;
                        entry.Size = file.Length;

                        using (FileStream fs = file.OpenRead()) {
                            crc.Reset();
                            long len = fs.Length;
                            while (len > 0) {
                                int readSoFar = fs.Read(buffer, 0, buffer.Length);
                                crc.Update(buffer, 0, readSoFar);
                                len -= readSoFar;
                            }
                            entry.Crc = crc.Value;
                            zs.PutNextEntry(entry);

                            len = fs.Length;
                            fs.Seek(0, SeekOrigin.Begin);
                            while (len > 0) {
                                int readSoFar = fs.Read(buffer, 0, buffer.Length);
                                zs.Write(buffer, 0, readSoFar);
                                len -= readSoFar;
                            }
                        }
                        Log.LogMessage("  added \"{0}\".", name);
                    }
                    zs.Finish();
                }
                Log.LogMessage("Created zip file \"{0}\" successfully.", _zipFileName);
                return true;
            }
            catch (Exception exc) {
                Log.LogErrorFromException(exc);
                return false;
            }
            finally {
                if (zs != null) {
                    zs.Close();
                }
            }
        }