Exemplo n.º 1
0
 private void EnsureDirectoryEntry(string localtPath)
 {
     if (!_entries.Contains(localtPath))
     {
         _entries.Add(localtPath);
         _zipStream.PutNextEntry(_entryFactory.MakeDirectoryEntry(localtPath));
         _zipStream.CloseEntry();
     }
 }
Exemplo n.º 2
0
 private void WriteToZip()
 {
     using (var memoryStream = new MemoryStream())
     {
         using (ZipOutputStream output = new ZipOutputStream(memoryStream))
         {
             ZipEntryFactory fact = new ZipEntryFactory();
             var             dir  = fact.MakeDirectoryEntry("");
         }
     }
 }
Exemplo n.º 3
0
 private void ZipEmptyFolder(string folderName)
 {
     if (Directory.Exists(folderName))
     {
         string zipEntryFolderName = ZipEntry.CleanName(ZipEntryFileName(folderName));
         if (!m_ZippedFiles.ContainsKey(zipEntryFolderName))
         {
             ZipEntry entry = m_ZipEntryFactory.MakeDirectoryEntry(zipEntryFolderName);
             m_ZipStream.PutNextEntry(entry);
             m_ZippedFiles.Add(zipEntryFolderName, zipEntryFolderName);
         }
     }
 }
Exemplo n.º 4
0
        override public void Write(BackupEntry entry)
        {
            base.Write();

            Console.WriteLine("Compressing: " + entry.RealPath);
            ZipEntry ez;
            string   entryPath = Path.GetPathRoot(entry.RealPath).Remove(1) + "/";

            if (entry.Info.IsDirectory)
            {
                entryPath += _zipFactory.NameTransform.TransformDirectory(entry.RealPath);
                ez         = _zipFactory.MakeDirectoryEntry(entryPath, false);
            }
            else if (entry.Info.IsFile)
            {
                // Windows specific metadata (timestamps)
                NTTaggedData meta = new NTTaggedData();
                meta.CreateTime           = entry.Info.Created;
                meta.LastModificationTime = entry.Info.LastModified;
                meta.LastAccessTime       = entry.Info.LastAccessed;

                entryPath   += _zipFactory.NameTransform.TransformFile(entry.RealPath);
                ez           = _zipFactory.MakeFileEntry(entryPath, false);
                ez.DateTime  = entry.Info.LastModified;
                ez.ExtraData = meta.GetData();
            }
            else
            {
                return;
            }

            _zip.PutNextEntry(ez);

            if (entry.Info.IsFile)
            {
                using (Stream fs = entry.Stream)
                {
                    int sourceBytes;
                    do
                    {
                        sourceBytes = fs.Read(_buffer, 0, _buffer.Length);
                        _zip.Write(_buffer, 0, sourceBytes);
                    } while (sourceBytes > 0);
                }
            }
        }
Exemplo n.º 5
0
        public void CreatedValues()
        {
            string tempDir = GetTempFilePath();

            Assert.IsNotNull(tempDir, "No permission to execute this test?");

            tempDir = Path.Combine(tempDir, "SharpZipTest");

            if (tempDir != null)
            {
                Directory.CreateDirectory(tempDir);

                try
                {
                    // Note the seconds returned will be even!
                    var createTime     = new DateTime(2100, 2, 27, 11, 07, 56);
                    var lastWriteTime  = new DateTime(2050, 11, 3, 7, 23, 32);
                    var lastAccessTime = new DateTime(2050, 11, 3, 0, 42, 12);

                    string tempFile = Path.Combine(tempDir, "SharpZipTest.Zip");
                    using (FileStream f = File.Create(tempFile, 1024))
                    {
                        f.WriteByte(0);
                    }

                    File.SetCreationTime(tempFile, createTime);
                    File.SetLastWriteTime(tempFile, lastWriteTime);
                    File.SetLastAccessTime(tempFile, lastAccessTime);

                    FileAttributes attributes = FileAttributes.Hidden;

                    File.SetAttributes(tempFile, attributes);
                    ZipEntryFactory factory = null;
                    ZipEntry        entry;
                    int             combinedAttributes = 0;

                    try
                    {
                        factory = new ZipEntryFactory();

                        factory.Setting       = ZipEntryFactory.TimeSetting.CreateTime;
                        factory.GetAttributes = ~((int)FileAttributes.ReadOnly);
                        factory.SetAttributes = (int)FileAttributes.ReadOnly;
                        combinedAttributes    = (int)(FileAttributes.ReadOnly | FileAttributes.Hidden);

                        entry = factory.MakeFileEntry(tempFile);
                        Assert.AreEqual(createTime, entry.DateTime, "Create time failure");
                        Assert.AreEqual(entry.ExternalFileAttributes, combinedAttributes);
                        Assert.AreEqual(1, entry.Size);

                        factory.Setting = ZipEntryFactory.TimeSetting.LastAccessTime;
                        entry           = factory.MakeFileEntry(tempFile);
                        Assert.AreEqual(lastAccessTime, entry.DateTime, "Access time failure");
                        Assert.AreEqual(1, entry.Size);

                        factory.Setting = ZipEntryFactory.TimeSetting.LastWriteTime;
                        entry           = factory.MakeFileEntry(tempFile);
                        Assert.AreEqual(lastWriteTime, entry.DateTime, "Write time failure");
                        Assert.AreEqual(1, entry.Size);
                    }
                    finally
                    {
                        File.Delete(tempFile);
                    }

                    // Do the same for directories
                    // Note the seconds returned will be even!
                    createTime     = new DateTime(2090, 2, 27, 11, 7, 56);
                    lastWriteTime  = new DateTime(2107, 12, 31, 23, 59, 58);
                    lastAccessTime = new DateTime(1980, 1, 1, 1, 0, 0);

                    Directory.SetCreationTime(tempDir, createTime);
                    Directory.SetLastWriteTime(tempDir, lastWriteTime);
                    Directory.SetLastAccessTime(tempDir, lastAccessTime);

                    factory.Setting = ZipEntryFactory.TimeSetting.CreateTime;
                    entry           = factory.MakeDirectoryEntry(tempDir);
                    Assert.AreEqual(createTime, entry.DateTime, "Directory create time failure");
                    Assert.IsTrue((entry.ExternalFileAttributes & (int)FileAttributes.Directory) == (int)FileAttributes.Directory);

                    factory.Setting = ZipEntryFactory.TimeSetting.LastAccessTime;
                    entry           = factory.MakeDirectoryEntry(tempDir);
                    Assert.AreEqual(lastAccessTime, entry.DateTime, "Directory access time failure");

                    factory.Setting = ZipEntryFactory.TimeSetting.LastWriteTime;
                    entry           = factory.MakeDirectoryEntry(tempDir);
                    Assert.AreEqual(lastWriteTime, entry.DateTime, "Directory write time failure");
                }
                finally
                {
                    Directory.Delete(tempDir, true);
                }
            }
        }
Exemplo n.º 6
0
        public void CreatedDirectoryEntriesUsesExpectedTime(ZipEntryFactory.TimeSetting timeSetting)
        {
            string tempDir = GetTempFilePath();

            if (tempDir == null)
            {
                Assert.Inconclusive("No permission to execute this test?");
            }

            tempDir = Path.Combine(tempDir, "SharpZipTest");

            // Note the seconds returned will be even!
            var expectedTime = new DateTime(2100, 2, 27, 11, 07, 56);

            Directory.CreateDirectory(tempDir);

            try
            {
                string tempFile = Path.Combine(tempDir, "SharpZipTest.Zip");

                using (FileStream f = File.Create(tempFile, 1024))
                {
                    f.WriteByte(0);
                }

                DateTime dirTime = DateTime.MinValue;

                if (timeSetting == ZipEntryFactory.TimeSetting.CreateTime)
                {
                    Directory.SetCreationTime(tempFile, expectedTime);
                    dirTime = Directory.GetCreationTime(tempDir);
                }

                if (timeSetting == ZipEntryFactory.TimeSetting.LastAccessTime)
                {
                    Directory.SetLastAccessTime(tempDir, expectedTime);
                    dirTime = Directory.GetLastAccessTime(tempDir);
                }

                if (timeSetting == ZipEntryFactory.TimeSetting.LastWriteTime)
                {
                    Directory.SetLastWriteTime(tempDir, expectedTime);
                    dirTime = Directory.GetLastWriteTime(tempDir);
                }

                if (dirTime != expectedTime)
                {
                    Assert.Inconclusive("Directory time could not be altered");
                }

                var factory = new ZipEntryFactory();

                factory.Setting = timeSetting;

                var entry = factory.MakeDirectoryEntry(tempDir);
                Assert.AreEqual(expectedTime, entry.DateTime);
            }
            finally
            {
                Directory.Delete(tempDir, true);
            }
        }
Exemplo n.º 7
0
        public static string OutDiff(string base_dir, string cur_dir, string package_out_dir, string ver)
        {
            string base_md5_file = Path.Combine(base_dir, Config.getMd5File());
            string cur_md5_file  = Path.Combine(cur_dir, Config.getMd5File());

            if (!File.Exists(base_md5_file))
            {
                FormUpdate.GetInstance().appendLog("base md5 not found, begin gen");
                FileStream   fs = File.Create(base_md5_file);
                StreamWriter sw = new StreamWriter(fs);
                GenResMd5(base_dir, sw, base_dir);
                sw.Close();
            }

            if (!File.Exists(cur_md5_file))
            {
                FormUpdate.GetInstance().appendLog("base md5 not found, begin gen");
                FileStream   fs = File.Create(cur_md5_file);
                StreamWriter sw = new StreamWriter(fs);
                GenResMd5(cur_md5_file, sw, cur_dir);
                sw.Close();
            }

            //读取文件
            Dictionary <String, String> base_md5_dic = new Dictionary <string, string>();
            Dictionary <String, String> cur_md5_dic  = new Dictionary <string, string>();


            string[] line = File.ReadAllLines(base_md5_file);
            foreach (string t in line)
            {
                string[] md5_file = t.Split(':');
                if (md5_file.Length != 2)
                {
                    FormUpdate.GetInstance().appendLog("base dir get file key error:" + t);
                    continue;
                }
                base_md5_dic.Add(md5_file[0], md5_file[1]);
            }

            line = File.ReadAllLines(cur_md5_file);
            foreach (string t in line)
            {
                string[] md5_file = t.Split(':');
                if (md5_file.Length != 2)
                {
                    FormUpdate.GetInstance().appendLog("cur dir get file key error:" + t);
                    continue;
                }
                cur_md5_dic.Add(md5_file[0], md5_file[1]);
            }
            Dictionary <String, String> diff_dic = new Dictionary <string, string>();

            //get diff
            foreach (string key in cur_md5_dic.Keys)
            {
                if (!base_md5_dic.ContainsKey(key))
                {
                    diff_dic.Add(key, cur_md5_dic[key]);
                }
                else if (base_md5_dic[key].CompareTo(cur_md5_dic[key]) != 0)
                {
                    diff_dic.Add(key, cur_md5_dic[key]);
                }
            }

            //copy to package out
            string tmpDir = Path.Combine(package_out_dir.Substring(0, package_out_dir.LastIndexOf(Path.DirectorySeparatorChar)), "temp");

            if (Directory.Exists(tmpDir))
            {
                Directory.Delete(tmpDir, true);
            }
            Directory.CreateDirectory(tmpDir);

            foreach (String key in diff_dic.Keys)
            {
                string dir = key.Substring(0, key.LastIndexOf(Path.DirectorySeparatorChar));
                dir = Path.Combine(tmpDir, dir);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                File.Copy(Path.Combine(cur_dir, key), Path.Combine(tmpDir, key));
            }

            string[]      dires       = Directory.GetDirectories(tmpDir);
            List <string> directories = new List <string>();

            directories.AddRange(dires);
            string zip_file_path = Path.Combine(package_out_dir, "update_" + ver + ".zip");


            using (ZipOutputStream ZipStream = new ZipOutputStream(System.IO.File.Create(zip_file_path)))
            {
                ZipStream.SetLevel(9);
                ZipEntryFactory factory = new ZipEntryFactory();
                while (directories.Count > 0)
                {
                    List <string> tmp = new List <string>();
                    foreach (string dir in directories)
                    {
                        string[] dirs = Directory.GetDirectories(dir);
                        if (dirs.Length > 0)
                        {
                            tmp.AddRange(dirs);
                        }
                    }
                    //add files to zip
                    foreach (string dir_tmp in directories)
                    {
                        string virtualDirectory = dir_tmp.Replace(tmpDir, string.Empty);
                        Log("add virtual dir:" + virtualDirectory);
                        ZipEntry zipEntry = factory.MakeDirectoryEntry(virtualDirectory);
                        zipEntry.DateTime = DateTime.Now;
                        ZipStream.PutNextEntry(zipEntry);
                        string[] files_tmp = Directory.GetFiles(dir_tmp);
                        foreach (string file_path in files_tmp)
                        {
                            string   entry_name = file_path.Replace(tmpDir, string.Empty);
                            ZipEntry entry      = factory.MakeFileEntry(entry_name);
                            entry.DateTime = DateTime.Now;
                            ZipStream.PutNextEntry(entry);
                            byte[] buffer = new byte[10240];
                            using (FileStream fs = System.IO.File.OpenRead(file_path))
                            {
                                int sourceBytes;
                                do
                                {
                                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                    ZipStream.Write(buffer, 0, sourceBytes);
                                } while (sourceBytes > 0);
                            }
                        }
                    }
                    directories = tmp;
                }
                ZipStream.Finish();
                ZipStream.Close();
            }
            //FastZip zip = new FastZip();
            //zip.CreateZip(zip_file_path, tmpDir, true, "");
            return(zip_file_path);
        }
Exemplo n.º 8
0
        /// <summary>
        /// 创建zip  directories 和 filenames 是对应的
        /// </summary>
        /// <param name="directories">文件目录</param>
        /// <param name="filenames">文件路径</param>
        /// <param name="zipFileName">文件名及路径</param>
        /// <param name="dic">所在目录</param>
        /// <param>进行对加密文件压缩下载</param>
        public static bool CreateZip(List <string> directories, IEnumerable <string> filenames, IEnumerable <string> displayNames, string zipFileName, string dir)
        {
            if (!System.IO.Directory.Exists(dir + "/zip/"))
            {
                System.IO.Directory.CreateDirectory(dir + "/zip/");
            }
            using (ZipOutputStream ZipStream = new ZipOutputStream(System.IO.File.Create(dir + "/zip/" + zipFileName)))
            {
                ZipStream.SetLevel(9);
                ZipEntryFactory factory = new ZipEntryFactory();
                foreach (var directory in directories)
                {
                    if (!string.IsNullOrEmpty(directory))
                    {
                        string   virtualDirectory = directory;
                        ZipEntry zipEntry         = factory.MakeDirectoryEntry(virtualDirectory);
                        zipEntry.DateTime = DateTime.Now;
                        ZipStream.PutNextEntry(zipEntry);
                    }
                }

                byte[] buffer = new byte[4096];
                for (int i = 0; i < filenames.Count(); i++)
                {
                    string file = filenames.ElementAt(i);
                    if (!string.IsNullOrEmpty(file))
                    {
                        string   newfileName = displayNames.ElementAt(i);
                        ZipEntry entry;
                        if (!string.IsNullOrEmpty(directories[i]))
                        {
                            entry = factory.MakeFileEntry(directories[i] + "//" + newfileName);
                        }
                        else
                        {
                            entry = factory.MakeFileEntry(newfileName);
                        }

                        entry.DateTime = DateTime.Now;
                        ZipStream.PutNextEntry(entry);
                        using (FileStream fs = System.IO.File.OpenRead(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                ZipStream.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }
                }
                ZipStream.Finish();
                ZipStream.Close();
            }



            //解决Firefox等下载文件名乱码问题
            //1、添加编码规则Response.HeaderEncoding Response.ContentEncoding 为 utf-8
            System.Web.HttpContext.Current.Response.HeaderEncoding  = Encoding.UTF8;
            System.Web.HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;


            System.Web.HttpContext.Current.Response.ContentType = "application/x-compress zip";
            //2、头部分 Content-Disposition 的设置要按照 rfc231 要求,  应该按照如下格式设置: "Content-Disposition","attachment;filename*=utf-8'zh_cn'文件名.xx"
            //   关键是 filename的设置,*= 后面是 两个单引号,分成三部分(编码 语言 文件名) 如:*=utf-8'zh_cn'文件名.xx 或者 *=utf-8' '文件名.xx

            //在Firefox中,保存时文件名中空格后面的内容会被截断(老的解决方法,不全面)
            //System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + zipFileName + "\"");
            System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename*=utf-8''{0}", HttpUtility.UrlPathEncode(zipFileName)));


            System.Web.HttpContext.Current.Response.TransmitFile(dir + "/zip/" + zipFileName);
            return(true);
        }
Exemplo n.º 9
0
        public void AddDirectory(string directoryName)
        {
            ZipEntry entry = factory.MakeDirectoryEntry(directoryName);

            ZipStream.PutNextEntry(entry);
        }