Пример #1
0
        public void UnicodeText()
        {
            var zippy   = new FastZip();
            var factory = new ZipEntryFactory();

            factory.IsUnicodeText = true;
            zippy.EntryFactory    = factory;

            string tempFilePath = GetTempFilePath();

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

            const string tempName1 = "a.dat";
            string       addFile   = Path.Combine(tempFilePath, tempName1);

            MakeTempFile(addFile, 1);

            try {
                var target = new MemoryStream();
                zippy.CreateZip(target, tempFilePath, false, Regex.Escape(tempName1), null);

                var archive = new MemoryStream(target.ToArray());

                using (ZipFile z = new ZipFile(archive)) {
                    Assert.AreEqual(1, z.Count);
                    Assert.IsTrue(z[0].IsUnicodeText);
                }
            } finally {
                File.Delete(addFile);
            }
        }
Пример #2
0
        public static async Task Make(RISCVIntegrationContext context)
        {
            var zipFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            try
            {
                using (var client = new HttpClient())
                {
                    var url = $"{context.Endpoint.RISCV}/make/{context.MakeTarget}";
                    var zfe = new ZipEntryFactory {
                        IsUnicodeText = true
                    };
                    context.RootFolder.CompressFolder(zipFile);
                    var content = File.ReadAllBytes(zipFile);

                    var response = await client.PostAsync(url, new StreamContent(new MemoryStream(content)));

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        var exception = await response.Content.ReadAsStringAsync();

                        throw new Exception(exception);
                    }
                    content = await response.Content.ReadAsByteArrayAsync();

                    File.WriteAllBytes(zipFile, content);
                    zipFile.ExtractZip(context.RootFolder);
                }
            }
            finally
            {
                zipFile.DeleteFileIfExists();
            }
        }
Пример #3
0
        public void UnicodeText()
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedFastZip zippy   = new IsolatedFastZip();
                ZipEntryFactory factory = new ZipEntryFactory();
                factory.IsUnicodeText = true;
                zippy.EntryFactory    = factory;

                string tempFilePath = GetTempFilePath();
                Assert.IsNotNull(tempFilePath, "No permission to execute this test?");

                const string tempName1 = "a.dat";
                string       addFile   = Path.Combine(tempFilePath, tempName1);
                MakeTempFile(addFile, 1);

                try
                {
                    MemoryStream target = new MemoryStream();
                    zippy.CreateZip(target, tempFilePath, false, tempName1, null); // failing here in 4

                    MemoryStream archive = new MemoryStream(target.ToArray());

                    using (IsolatedZipFile z = new IsolatedZipFile(archive))
                    {
                        Assert.AreEqual(1, z.Count);
                        Assert.IsTrue(z[0].IsUnicodeText);
                    }
                }
                finally
                {
                    store.DeleteFile(addFile);
                }
            }
        }
Пример #4
0
        public void Defaults()
        {
            DateTime testStart = DateTime.Now;
            var      f         = new ZipEntryFactory();

            Assert.IsNotNull(f.NameTransform);
            Assert.AreEqual(-1, f.GetAttributes);
            Assert.AreEqual(0, f.SetAttributes);
            Assert.AreEqual(ZipEntryFactory.TimeSetting.LastWriteTime, f.Setting);

            Assert.LessOrEqual(testStart, f.FixedDateTime);
            Assert.GreaterOrEqual(DateTime.Now, f.FixedDateTime);

            f = new ZipEntryFactory(ZipEntryFactory.TimeSetting.LastAccessTimeUtc);
            Assert.IsNotNull(f.NameTransform);
            Assert.AreEqual(-1, f.GetAttributes);
            Assert.AreEqual(0, f.SetAttributes);
            Assert.AreEqual(ZipEntryFactory.TimeSetting.LastAccessTimeUtc, f.Setting);
            Assert.LessOrEqual(testStart, f.FixedDateTime);
            Assert.GreaterOrEqual(DateTime.Now, f.FixedDateTime);

            var fixedDate = new DateTime(1999, 1, 2);

            f = new ZipEntryFactory(fixedDate);
            Assert.IsNotNull(f.NameTransform);
            Assert.AreEqual(-1, f.GetAttributes);
            Assert.AreEqual(0, f.SetAttributes);
            Assert.AreEqual(ZipEntryFactory.TimeSetting.Fixed, f.Setting);
            Assert.AreEqual(fixedDate, f.FixedDateTime);
        }
Пример #5
0
        public ZipFileBuilder(Stream outStream)
        {
            zipStream = new ZipOutputStream(outStream);
            zipStream.SetLevel(9); //best compression

            factory = new ZipEntryFactory(DateTime.Now);
        }
Пример #6
0
Файл: Zip.cs Проект: PGIMES/MES
    //全部下载
    public string GetFile(string files, string MapPath, string m_sid)
    {
        string[] ls_files = files.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);

        //string wjj = m_sid == "" ? DateTime.Now.ToString("yyyyMMdd") : m_sid;
        //string tmp_dir = MapPath + @"\UploadFile\Purchase\" + wjj + @"\zip_temp\";


        string wjj     = m_sid == "" ? DateTime.Now.ToString("yyyyMMdd") : m_sid;
        string tmp_dir = MapPath + @"\ExportFile\Zip\" + wjj + @"\";

        if (!Directory.Exists(tmp_dir))
        {
            Directory.CreateDirectory(tmp_dir);
        }
        string filename     = DateTime.Now.ToString("yyyyMMddhhmmssff") + ".zip";
        string filepath_zip = tmp_dir + filename;

        string newfilename = string.Empty;
        string sourcefile  = string.Empty;

        ZipEntryFactory zipEntryFactory = new ZipEntryFactory();

        using (ZipOutputStream outPutStream = new ZipOutputStream(System.IO.File.Create(filepath_zip)))
        {
            outPutStream.SetLevel(5);
            ZipEntry entry  = null;
            byte[]   buffer = null;

            for (int i = 0; i < ls_files.Length; i++)
            {
                string[] ls_files_2 = ls_files[i].Split(',');
                if (ls_files_2.Length == 3)
                {
                    newfilename = ls_files_2[0].ToString();
                    sourcefile  = MapPath + ls_files_2[1].ToString();
                }
                else//之前的文件,只有一个路径
                {
                    string   s  = ls_files_2[0].ToString();
                    string[] ss = s.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries);
                    newfilename = ss[ss.Length - 1].ToString(); //"文件浏览";

                    sourcefile = MapPath + ls_files_2[0].ToString();
                }

                buffer = new byte[4096];
                entry  = zipEntryFactory.MakeFileEntry(newfilename);
                outPutStream.PutNextEntry(entry);
                using (FileStream fileStream = File.OpenRead(sourcefile))
                {
                    StreamUtils.Copy(fileStream, outPutStream, buffer);
                }
            }
            outPutStream.Finish();
            outPutStream.Close();
        }

        return(filepath_zip);
    }
Пример #7
0
        //  -------------------------------------------------------------------
        /// <summary>
        /// Starts a new package that will be written to the specified stream.
        /// </summary>
        /// <param name="stream">
        /// The stream to which the package will be written.
        /// </param>
        /// <param name="parameters">
        /// A dictionary of parameters that are specified in the target
        /// definition.
        /// </param>
        public void StartPackage(Stream stream,
                                 Dictionary <string, string> parameters)
        {
            zipStream  = new ZipOutputStream(stream);
            zipFactory = new ZipEntryFactory();

            buffer = new byte[BufferSize];
        }
Пример #8
0
 public SolZipController(string zipFileName, bool excludeSZReadme, bool removeSourceControl)
 {
     m_ExcludeSZReadme     = excludeSZReadme;
     m_RemoveSourceControl = removeSourceControl;
     m_TopPath             = string.Empty;
     m_FileStream          = new FileStream(zipFileName, FileMode.CreateNew, FileAccess.Write);
     m_ZipStream           = new ZipOutputStream(m_FileStream);
     m_ZipEntryFactory     = new ZipEntryFactory(ZipEntryFactory.TimeSetting.CreateTimeUtc);
 }
Пример #9
0
        override public void Init()
        {
            base.Init();

            _buffer       = new byte[4096];
            _zipFactory   = new ZipEntryFactory();
            _zip          = new ZipOutputStream(File.Create(_cfg.Target));
            _zip.UseZip64 = UseZip64.Dynamic;
            //_zip.SetLevel(8);
            _zip.SetComment(_cfg.Flags["incremental"] ? "Incremental backup" : "Full backup");
        }
Пример #10
0
 public scanDirParams(ZipOutputStream zip, string sourceDirectory, ZipEntryFactory entryFactory, ProgressHandler progress, IStringFilter nf, IStringFilter df)
 {
     Zip             = zip;
     EntryFactory    = entryFactory;
     Progress        = progress;
     NameFilter      = nf;
     DirFilter       = df;
     DirEntries      = new Dictionary <string, ZipFSEntry>(StringComparer.InvariantCultureIgnoreCase);
     SourceDirectory = Utils.BackslashAdd(new DirectoryInfo(sourceDirectory).FullName);
     Buffer          = new byte[16384];
 }
Пример #11
0
 private void WriteToZip()
 {
     using (var memoryStream = new MemoryStream())
     {
         using (ZipOutputStream output = new ZipOutputStream(memoryStream))
         {
             ZipEntryFactory fact = new ZipEntryFactory();
             var             dir  = fact.MakeDirectoryEntry("");
         }
     }
 }
Пример #12
0
 public WebStructureOutput(string webTitle, bool createWebFolder = false)
 {
     _webTitle                = webTitle;
     _createWebFolder         = createWebFolder;
     _memoryStream            = new MemoryStream();
     _entries                 = new HashSet <string>();
     _entryFactory            = new ZipEntryFactory();
     _zipStream               = new ZipOutputStream(_memoryStream);
     _zipStream.IsStreamOwner = false;
     _hasData                 = false;
 }
        public static void CompressFolder(this string directoryPath, string zipFileName)
        {
            var zfe = new ZipEntryFactory {
                IsUnicodeText = true
            };
            var fastZip = new FastZip()
            {
                EntryFactory = zfe
            };

            fastZip.CreateZip(zipFileName, directoryPath, true, null);
        }
Пример #14
0
        public void CreatedFileEntriesUsesExpectedAttributes()
        {
            string tempDir = GetTempFilePath();

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

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

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

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

                FileAttributes attributes = FileAttributes.Hidden;

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

                try
                {
                    factory = new ZipEntryFactory();

                    factory.GetAttributes = ~((int)FileAttributes.ReadOnly);
                    factory.SetAttributes = (int)FileAttributes.ReadOnly;
                    combinedAttributes    = (int)(FileAttributes.ReadOnly | FileAttributes.Hidden);

                    entry = factory.MakeFileEntry(tempFile);
                    Assert.AreEqual(entry.ExternalFileAttributes, combinedAttributes);
                    Assert.AreEqual(1, entry.Size);
                }
                finally
                {
                    File.Delete(tempFile);
                }
            }
            finally
            {
                Directory.Delete(tempDir, true);
            }
        }
Пример #15
0
        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)));
            }
        }
Пример #16
0
        private static void ZipCopyToZip(string sourceApkFile, string inputDir, IEnumerable <string> files, string outputFile)
        {
            HashSet <string> filesSet = new HashSet <string>(files.Select(file => file));

            using (ZipInputStream zipInput = new ZipInputStream(File.OpenRead(sourceApkFile)))
                using (ZipOutputStream zipOutput = new ZipOutputStream(File.Create(outputFile, 4096, FileOptions.SequentialScan))) {
                    zipOutput.UseZip64 = UseZip64.Off;

                    ZipEntryFactory factory = new ZipEntryFactory();
                    ZipEntry        entry;
                    while ((entry = zipInput.GetNextEntry()) != null)
                    {
                        ZipEntry entry2 = factory.MakeFileEntry(entry.Name);
                        entry2.DosTime = entry.DosTime;
                        zipOutput.PutNextEntry(entry2);

                        if (filesSet.Remove(entry.Name))
                        {
                            using (var temp = File.OpenRead(inputDir + '\\' + entry.Name)) {
                                temp.CopyTo(zipOutput);
                            }
                        }
                        else
                        {
                            zipInput.CopyTo(zipOutput);
                        }
                    }

                    foreach (var file in filesSet)
                    {
                        entry          = factory.MakeFileEntry(file);
                        entry.DateTime = new FileInfo(inputDir + '\\' + entry.Name).LastWriteTime;
                        zipOutput.PutNextEntry(entry);
                        using (var temp = File.OpenRead(inputDir + '\\' + entry.Name)) {
                            temp.CopyTo(zipOutput);
                        }
                    }
                }
        }
Пример #17
0
        /// <summary>
        /// Wraps the given IndexFile and all provided files into a wrapper file
        /// </summary>
        /// <param name="map">the FileMap used to map the files from FileSystem to the archive file</param>
        /// <param name="wrappedName">the name of the taret wrapper-file</param>
        /// <param name="password">the password that is used for encryption</param>
        public void WrapFiles(FileMap map, string wrappedName, string password)
        {
            using (FileStream fst = new FileStream(wrappedName, FileMode.Create, FileAccess.ReadWrite))
            {
                using (ZipOutputStream zos = new ZipOutputStream(fst))
                {
                    if (password != null)
                    {
                        zos.Password = password;
                    }

                    zos.SetLevel(compressionLevel);
                    ZipEntryFactory fac = new ZipEntryFactory {
                        IsUnicodeText = true
                    };
                    LogEnvironment.LogDebugEvent(null, (from t in map
                                                        select
                                                        WriteEntry(t,
                                                                   fac.MakeFileEntry(t.LocationInFileSystem, t.ArchiveFileName, true),
                                                                   zos, password != null ? 256 : 0)).Count().ToString(), (int)LogSeverity.Report, null);
                }
            }
        }
Пример #18
0
        public void CreateInMemoryValues()
        {
            string tempFile = "bingo:";

            // Note the seconds returned will be even!
            var epochTime      = new DateTime(1980, 1, 1);
            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);

            var      factory = new ZipEntryFactory();
            ZipEntry entry;
            int      combinedAttributes;

            DateTime startTime = DateTime.Now;

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

            entry = factory.MakeFileEntry(tempFile, false);
            Assert.IsTrue(TestHelper.CompareDosDateTimes(startTime, entry.DateTime) <= 0, "Create time failure");
            Assert.AreEqual(entry.ExternalFileAttributes, combinedAttributes);
            Assert.AreEqual(-1, entry.Size);

            factory.FixedDateTime = startTime;
            factory.Setting       = ZipEntryFactory.TimeSetting.Fixed;
            entry = factory.MakeFileEntry(tempFile, false);
            Assert.AreEqual(0, TestHelper.CompareDosDateTimes(startTime, entry.DateTime), "Access time failure");
            Assert.AreEqual(-1, entry.Size);

            factory.Setting = ZipEntryFactory.TimeSetting.LastWriteTime;
            entry           = factory.MakeFileEntry(tempFile, false);
            Assert.IsTrue(TestHelper.CompareDosDateTimes(startTime, entry.DateTime) <= 0, "Write time failure");
            Assert.AreEqual(-1, entry.Size);
        }
Пример #19
0
        static void PackageExtension(string path)
        {
            parentPath = Path.GetDirectoryName(path);
            AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs erArgs) =>
            {
                string strFileName = erArgs.Name.Split(',')[0];
                string dllPath     = $"{parentPath}/{strFileName}.dll";
                return(Assembly.LoadFile(dllPath));
            };
            Installation installation = new Installation()
            {
                FileList         = new List <string>(),
                Dependencies     = new List <Dependency>(),
                MetaDependencies = new List <MetaDependency>(),
                UpdateLog        = new Stack <UpdateLog>()
            };
            List <MetaDependency> metaList      = new List <MetaDependency>();
            List <Dependency>     extensionList = new List <Dependency>();
            List <string>         depList       = new List <string>();
            bool isMeta = false;

            if (path.EndsWith(".Meta.dll"))
            {
                Assembly metaAssembly = Assembly.LoadFile(path);
                installation.Id = metaAssembly.GetName().Name;
                installation.FileList.Add($"extension_metas/{installation.Id}.dll");
                isMeta = true;
            }
            else
            {
                Assembly extensionAssembly = Assembly.LoadFile(path);
                installation.Id = extensionAssembly.GetName().Name;
                bool hasValidExtension = false;
                foreach (Type t in extensionAssembly.GetTypes())
                {
                    if (t.GetInterface("IExtension") != null)
                    {
                        hasValidExtension = true;
                    }
                }

                if (!hasValidExtension)
                {
                    Console.WriteLine("valid extension not found!");
                    Console.WriteLine("exiting...");
                    Console.ReadKey();
                    return;
                }

                AssemblyName[] referencedAssemblyList;
                referencedAssemblyList = extensionAssembly.GetReferencedAssemblies();


                foreach (var assemblyName in referencedAssemblyList)
                {
                    if (File.Exists($"{parentPath}/{assemblyName.Name}.dll") && assemblyName.Name != "Fishery.Core")
                    {
                        if (assemblyName.Name.EndsWith(".Meta"))
                        {
                            metaList.Add(new MetaDependency()
                            {
                                Name = assemblyName.Name
                            });
                        }
                        else if (IsExtension($"{parentPath}/{assemblyName.Name}.dll"))
                        {
                            extensionList.Add(new Dependency()
                            {
                                Name = assemblyName.Name
                            });
                        }
                        else
                        {
                            depList.Add(assemblyName.Name);
                        }
                    }
                }
            }

            Installation latestInstallation = GetExistPackageInfo(installation.Id);

            foreach (var dependency in metaList)
            {
                var prevDependency = latestInstallation?.MetaDependencies.Find(m => m.Name == dependency.Name);
                if (prevDependency != null)
                {
                    dependency.VersionCode = prevDependency.VersionCode;
                }
                dependency.VersionCode =
                    ReadInt($"Which version of the [Meta]{dependency.Name} is using?", "VersionCode", dependency.VersionCode.ToString());
                installation.MetaDependencies.Add(dependency);
            }

            foreach (var dependency in extensionList)
            {
                var prevDependency = latestInstallation?.Dependencies.Find(m => m.Name == dependency.Name);
                if (prevDependency != null)
                {
                    dependency.VersionCode = prevDependency.VersionCode;
                }
                dependency.VersionCode =
                    ReadInt($"Which version of the [Extension]{dependency.Name} is using?", "VersionCode", dependency.VersionCode.ToString());
                installation.Dependencies.Add(dependency);
            }

            foreach (var dep in depList)
            {
                List <string> depReferenceList = ResolveDependencyReferenceList(dep);
                foreach (var depReference in depReferenceList)
                {
                    installation.FileList.Add($"dependencies/{installation.Id}/{depReference}.dll");
                }
            }


            bool useExistInfo = false;

            if (latestInstallation != null)
            {
                useExistInfo =
                    ReadString("Find last version of the extension use exist info?", "[Y/y]", "Y").ToUpper() == "Y";
                if (latestInstallation.UpdateLog.Count > 4)
                {
                    installation.UpdateLog = new Stack <UpdateLog>(latestInstallation.UpdateLog.Take(4));
                }
                else
                {
                    installation.UpdateLog = new Stack <UpdateLog>(latestInstallation.UpdateLog.Take(latestInstallation.UpdateLog.Count));
                }
            }

            if (useExistInfo)
            {
                installation.Name    = latestInstallation.Name;
                installation.Author  = latestInstallation.Author;
                installation.Summary = latestInstallation.Summary;
            }
            else
            {
                installation.Name    = ReadString("What's the friendly name of this extension", "Name");
                installation.Author  = ReadString("What's your name", "Author");
                installation.Summary = ReadString("What's the description of the extension", "Summary");
            }

            installation.VersionCode = ReadInt("What's the version code of the extension", "VersionCode",
                                               latestInstallation != null ? (latestInstallation.VersionCode + 1).ToString() : "");
            installation.Version = ReadString("What's the version of the extension", "Version",
                                              ConvertVersionCodeToVersionString(installation.VersionCode));
            if (latestInstallation != null)
            {
                UpdateLog updateLog = new UpdateLog();
                if (installation.VersionCode <= latestInstallation.VersionCode)
                {
                    Console.WriteLine("The version what you entered was lower than latest!");
                    Console.ReadKey();
                    return;
                }

                updateLog.OriginalVersion     = latestInstallation.Version;
                updateLog.OriginalVersionCode = latestInstallation.VersionCode;
                updateLog.TargetVersion       = installation.Version;
                updateLog.TargetVersionCode   = installation.VersionCode;
                updateLog.UpdateContent       = ReadString("What has been updated?", "Content");
                installation.UpdateLog.Push(updateLog);
            }

            installation.EntryPoint = "";
            if (!isMeta)
            {
                installation.EntryPoint = "extensions/" + installation.Id + ".dll";
                installation.FileList.Add(installation.EntryPoint);
            }

            FileStream fileStream = new FileStream(
                $"{rootPath}/{(isMeta ? "metas" : "extensions")}/{installation.Id}.{installation.VersionCode}.zip",
                FileMode.OpenOrCreate);
            ZipOutputStream zipOutputStream = new ZipOutputStream(fileStream);
            ZipEntryFactory zipEntryFactory = new ZipEntryFactory();

            byte[] buffer = new byte[4096];
            foreach (var filePath in installation.FileList)
            {
                ZipEntry entry = zipEntryFactory.MakeFileEntry(filePath);
                zipOutputStream.PutNextEntry(entry);
                StreamUtils.Copy(
                    new FileStream($"{parentPath}/{Path.GetFileName(filePath)}", FileMode.Open, FileAccess.Read,
                                   FileShare.Read), zipOutputStream, buffer);
                zipOutputStream.CloseEntry();
            }

            zipOutputStream.PutNextEntry(zipEntryFactory.MakeFileEntry("info.json"));
            StreamUtils.Copy(new MemoryStream(Encoding.UTF8.GetBytes(new Serializer().SerializeToString(installation))),
                             zipOutputStream, buffer);
            zipOutputStream.CloseEntry();
            zipOutputStream.Close();
            fileStream.Close();
            if (latestInstallation == null)
            {
                _repoExtensionList.Add(installation.Id, new List <Installation>()
                {
                    installation
                });
            }
            else
            {
                _repoExtensionList[installation.Id].Add(installation);
            }
            new Serializer().SerializeToFile(_repoExtensionList,
                                             AppDomain.CurrentDomain.BaseDirectory + "/repo.json");
            Console.WriteLine($"{installation.Id}'s package file has been saved");
        }
Пример #20
0
        /// <summary>
        /// Appends the Files of a map to an existing Archive
        /// </summary>
        /// <param name="map">the map that contains files which need to be added to an archive</param>
        /// <param name="wrappedName">the name of the taret wrapper-file</param>
        /// <param name="password">the password for the existing and the new zip</param>
        public void AppendFiles(FileMap map, string wrappedName, string password)
        {
            bool existing = false;

            if (File.Exists(wrappedName))
            {
                File.Move(wrappedName, $"{wrappedName}.lock");
                existing = true;
            }


            using (FileStream fst = new FileStream(wrappedName, FileMode.Create, FileAccess.ReadWrite))
            {
                var keySize = password != null ? 256 : 0;
                using (ZipOutputStream zos = new ZipOutputStream(fst))
                {
                    if (password != null)
                    {
                        zos.Password = password;
                    }

                    zos.SetLevel(compressionLevel);
                    ZipEntryFactory fac = new ZipEntryFactory {
                        IsUnicodeText = true
                    };
                    LogEnvironment.LogDebugEvent(null, (from t in map
                                                        select
                                                        WriteEntry(t,
                                                                   fac.MakeFileEntry(t.LocationInFileSystem, t.ArchiveFileName, true),
                                                                   zos, keySize)).Count().ToString(), (int)LogSeverity.Report, null);

                    if (existing)
                    {
                        using (FileStream fsti = new FileStream($"{wrappedName}.lock", FileMode.Open, FileAccess.Read))
                        {
                            UnwrapZip(fsti, ".", true, oent =>
                            {
                                if (!map.Contains(oent.ArchiveFileName))
                                {
                                    var net = fac.MakeFileEntry(oent.ArchiveFileName, false);
                                    if (keySize > 0)
                                    {
                                        net.AESKeySize = keySize;
                                    }

                                    zos.PutNextEntry(net);
                                    return(zos);
                                }

                                return(null);
                            }, (input, output) =>
                            {
                                try
                                {
                                    input.CopyTo(output);
                                }
                                finally
                                {
                                    zos.CloseEntry();
                                }
                            }, true, null);
                        }
                    }
                }
            }
        }
Пример #21
0
        public string getZipFile(string filedata, string customer)
        {
            string dir     = @"d:/ftpserver/";
            string tmp_dir = @"d:/ftpserver/declare_tmp_zip/";

            if (!Directory.Exists(tmp_dir))
            {
                Directory.CreateDirectory(tmp_dir);
            }
            try
            {
                JArray j_array = JArray.Parse(filedata);

                string codelist = "(";
                int    i        = 0;
                foreach (JObject jo in j_array)
                {
                    codelist += "'" + jo["CODE"] + "'";
                    if (i != j_array.Count - 1)
                    {
                        codelist += ",";
                    }
                    i++;
                }
                codelist += ")";

                string    sql = @"select t.* from list_attachment t where t.filetype='61' and t.declcode in " + codelist + " order by pgindex asc,uploadtime asc";
                DataTable dt  = DBMgr.GetDataTable(sql);


                string filepath = string.Empty;
                //MemoryStream ms = new MemoryStream();
                ZipEntryFactory zipEntryFactory = new ZipEntryFactory();
                //ZipFile zipFile = new ZipFile(ms);
                string filename      = DateTime.Now.ToString("yyyyMMddhhmmssff") + ".zip";
                string newfilename   = string.Empty;
                string sourcefile    = string.Empty;
                string filepath_mask = string.Empty;
                string busitype      = string.Empty;
                using (ZipOutputStream outPutStream = new ZipOutputStream(System.IO.File.Create(tmp_dir + filename)))
                {
                    outPutStream.SetLevel(5);
                    ZipEntry entry  = null;
                    byte[]   buffer = null;
                    //foreach (DataRow dr in dt.Rows)
                    foreach (JObject jo in j_array)
                    {
                        DataRow[] drs = dt.Select("DECLCODE='" + jo["CODE"] + "'");
                        busitype      = jo["BUSITYPE"].ToString();
                        sourcefile    = drs[0]["FILENAME"].ToString();
                        filepath      = dir + sourcefile;
                        filepath_mask = AddBackground(filepath, "企业留存联", busitype, "", customer);
                        newfilename   = jo["DECLARATIONCODE"].ToString() + sourcefile.Substring(sourcefile.LastIndexOf("."));
                        buffer        = new byte[4096];
                        entry         = zipEntryFactory.MakeFileEntry(newfilename);
                        outPutStream.PutNextEntry(entry);
                        using (FileStream fileStream = File.OpenRead(filepath_mask))
                        {
                            StreamUtils.Copy(fileStream, outPutStream, buffer);
                        }
                    }
                    outPutStream.Finish();
                    outPutStream.Close();
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();

                return("/file/declare_tmp_zip/" + filename);
            }
            catch (Exception)
            {
                return("error");
            }
        }
Пример #22
0
        public void CreateInMemoryValues()
        {
            var tempFile = "bingo:";

            // Note the seconds returned will be even!
            var epochTime = new DateTime(1980, 1, 1);
            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);

            var factory = new ZipEntryFactory();
            ZipEntry entry;
            int combinedAttributes;

            var startTime = DateTime.Now;

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

            entry = factory.MakeFileEntry(tempFile, false);
            Assert.IsTrue(TestHelper.CompareDosDateTimes(startTime, entry.DateTime) <= 0, "Create time failure");
            Assert.AreEqual(entry.ExternalFileAttributes, combinedAttributes);
            Assert.AreEqual(-1, entry.Size);

            factory.FixedDateTime = startTime;
            factory.Setting = ZipEntryFactory.TimeSetting.Fixed;
            entry = factory.MakeFileEntry(tempFile, false);
            Assert.AreEqual(0, TestHelper.CompareDosDateTimes(startTime, entry.DateTime), "Access time failure");
            Assert.AreEqual(-1, entry.Size);

            factory.Setting = ZipEntryFactory.TimeSetting.LastWriteTime;
            entry = factory.MakeFileEntry(tempFile, false);
            Assert.IsTrue(TestHelper.CompareDosDateTimes(startTime, entry.DateTime) <= 0, "Write time failure");
            Assert.AreEqual(-1, entry.Size);
        }
Пример #23
0
        static async Task Main(string[] args)
        {
            try
            {
                var token          = args[0];
                var localDirectory = Path.GetFullPath(args[1]);
                if (!IsEndingWithSeparator(localDirectory))
                {
                    localDirectory += Path.DirectorySeparatorChar;
                }
                var dropboxDirectory = args[2];
                if (!IsEndingWithSeparator(dropboxDirectory))
                {
                    dropboxDirectory += Path.AltDirectorySeparatorChar;
                }
                string password = args[3];

                var newFiles = new HashSet <string>(
                    Directory.GetFiles(localDirectory, "*", SearchOption.AllDirectories)
                    .Select(f => f.Substring(localDirectory.Length)), StringComparer.OrdinalIgnoreCase);

                var filesToDelete = new HashSet <string>();

                using (var dropbox = new DropboxClient(token))
                {
                    try
                    {
                        await dropbox.Files.CreateFolderV2Async(dropboxDirectory.TrimEnd('/'));
                    }
                    catch
                    {
                    }


                    var existingFiles   = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase);
                    var existingFolders = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase);
                    existingFolders.Add("");

                    for (var list = await dropbox.Files.ListFolderAsync(dropboxDirectory.TrimEnd('/'), true, limit: 2000);
                         list != null;
                         list = list.HasMore ? await dropbox.Files.ListFolderContinueAsync(list.Cursor) : null)
                    {
                        foreach (var entry in list.Entries)
                        {
                            if (!entry.IsFile)
                            {
                                if (entry.IsFolder)
                                {
                                    existingFolders.Add(entry.AsFolder.PathLower);
                                }
                                continue;
                            }

                            existingFiles.Add(entry.PathLower);
                            var relativePath = entry.PathLower.Substring(dropboxDirectory.Length);
                            if (!relativePath.EndsWith(".zip"))
                            {
                                continue;
                            }
                            var withoutZip = relativePath.Substring(0, relativePath.Length - 4).Replace("/", Path.DirectorySeparatorChar + "");
                            if (newFiles.Contains(withoutZip))
                            {
                                var info = new FileInfo(Path.Combine(localDirectory, withoutZip));
                                if ((info.LastWriteTimeUtc - entry.AsFile.ClientModified).TotalSeconds < 1f)
                                {
                                    newFiles.Remove(withoutZip);
                                }
                            }
                            else
                            {
                                filesToDelete.Add(entry.PathLower);
                            }
                        }
                    }

                    await DeleteFilesBatchAsync();

                    ulong deletingAccumulatedSize = 0;

                    async Task DeleteFilesBatchAsync()
                    {
                        if (filesToDelete.Count > 0)
                        {
                            Console.WriteLine($"Deleting files: \n{string.Join("\n", filesToDelete)}");
                            var j = await dropbox.Files.DeleteBatchAsync(filesToDelete.Select(x => new DeleteArg(x)));

                            if (j.IsAsyncJobId)
                            {
                                for (DeleteBatchJobStatus r = await dropbox.Files.DeleteBatchCheckAsync(j.AsAsyncJobId.Value);
                                     r.IsInProgress;
                                     r = await dropbox.Files.DeleteBatchCheckAsync(j.AsAsyncJobId.Value))
                                {
                                    Thread.Sleep(5000);
                                }
                            }

                            filesToDelete.Clear();
                            deletingAccumulatedSize = 0;
                        }
                    }

                    if (newFiles.Count > 0)
                    {
                        Console.WriteLine($"Uploading files: {newFiles.Count}");
                        ZipStrings.UseUnicode = true;
                        ZipStrings.CodePage   = 65001;
                        var    entryFactory = new ZipEntryFactory();
                        byte[] msBuffer     = new byte[1000 * 1000 * 150];
                        int    bufferSize   = 1000 * 1000 * 140;
                        using var reader = new AsyncMultiFileReader(bufferSize, (f, t) => new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, true));
                        var newFilesList = newFiles.ToList();
                        for (int i = 0; i < newFilesList.Count; i++)
                        {
                            var relativePath = newFilesList[i];
                            Console.Write($" {relativePath}");
                            string fullPath = Path.Combine(localDirectory, relativePath);
                            reader.NextFile = (fullPath, null);
                            reader.OpenNextFile();
                            if (i < newFilesList.Count - 1)
                            {
                                reader.NextFile = (Path.Combine(localDirectory, newFilesList[i + 1]), null);
                            }

                            var info             = new FileInfo(fullPath);
                            var clientModifiedAt = info.LastWriteTimeUtc;
                            using (var zipWriterUnderlyingStream = new CopyStream())
                            {
                                var bufferStream = new MemoryStream(msBuffer);
                                bufferStream.SetLength(0);

                                UploadSessionStartResult session = null;
                                long offset = 0;

                                using (var zipWriter = new ZipOutputStream(zipWriterUnderlyingStream, bufferSize)
                                {
                                    IsStreamOwner = false, Password = password, UseZip64 = UseZip64.On
                                })
                                {
                                    try
                                    {
                                        zipWriterUnderlyingStream.CopyTo = bufferStream;
                                        zipWriter.SetLevel(0);
                                        var entry = entryFactory.MakeFileEntry(fullPath, '/' + Path.GetFileName(relativePath), true);
                                        entry.AESKeySize = 256;
                                        zipWriter.PutNextEntry(entry);

                                        int read;
                                        while ((read = reader.ReadNextBlock()) > 0)
                                        {
                                            Console.Write($"\r {relativePath} {offset / (double) info.Length * 100:F0}%");
                                            zipWriter.Write(reader.CurrentBuffer, 0, read);
                                            zipWriter.Flush();
                                            bufferStream.Position = 0;
                                            var length = bufferStream.Length;
                                            if (session == null)
                                            {
                                                session = await dropbox.Files.UploadSessionStartAsync(new UploadSessionStartArg(), bufferStream);
                                            }
                                            else
                                            {
                                                await dropbox.Files.UploadSessionAppendV2Async(new UploadSessionCursor(session.SessionId, (ulong)offset), false, bufferStream);
                                            }
                                            offset += length;
                                            zipWriterUnderlyingStream.CopyTo = bufferStream = new MemoryStream(msBuffer);
                                            bufferStream.SetLength(0);
                                        }

                                        Console.Write($"\r {relativePath} 100%");
                                        Console.WriteLine();

                                        zipWriter.CloseEntry();
                                        zipWriter.Finish();
                                        zipWriter.Close();
                                    }
                                    catch
                                    {
                                        // disposing ZipOutputStream causes writing to bufferStream
                                        if (!bufferStream.CanRead && !bufferStream.CanWrite)
                                        {
                                            zipWriterUnderlyingStream.CopyTo = bufferStream = new MemoryStream(msBuffer);
                                        }
                                        throw;
                                    }
                                }

                                bufferStream.Position = 0;
                                var commitInfo = new CommitInfo(Path.Combine(dropboxDirectory, relativePath.Replace("\\", "/")) + ".zip",
                                                                WriteMode.Overwrite.Instance,
                                                                false,
                                                                clientModifiedAt);

                                if (session == null)
                                {
                                    await dropbox.Files.UploadAsync(commitInfo, bufferStream);
                                }
                                else
                                {
                                    await dropbox.Files.UploadSessionFinishAsync(new UploadSessionCursor(session.SessionId, (ulong)offset), commitInfo, bufferStream);
                                }
                            }
                        }
                    }

                    Console.WriteLine("Recycling deleted files for endless storage");

                    const ulong deletingBatchSize = 1024UL * 1024 * 1024 * 32;

                    for (var list = await dropbox.Files.ListFolderAsync(dropboxDirectory.TrimEnd('/'), true, limit: 2000, includeDeleted: true);
                         list != null;
                         list = list.HasMore ? await dropbox.Files.ListFolderContinueAsync(list.Cursor) : null)
                    {
                        foreach (var entry in list.Entries)
                        {
                            if (!entry.IsDeleted || existingFiles.Contains(entry.PathLower))
                            {
                                continue;
                            }

                            var parentFolder = entry.PathLower;
                            int lastSlash    = parentFolder.LastIndexOf('/');
                            if (lastSlash == -1)
                            {
                                continue;
                            }
                            parentFolder = parentFolder.Substring(0, lastSlash);
                            if (!existingFolders.Contains(parentFolder))
                            {
                                continue;
                            }

                            ListRevisionsResult rev;
                            try
                            {
                                rev = await dropbox.Files.ListRevisionsAsync(entry.AsDeleted.PathLower, ListRevisionsMode.Path.Instance, 1);
                            }
                            catch
                            {
                                // get revisions doesn't work for folders but no way to check if it's a folder beforehand
                                continue;
                            }

                            if (!(DateTime.UtcNow - rev.ServerDeleted >= TimeSpan.FromDays(15)) || (DateTime.UtcNow - rev.ServerDeleted > TimeSpan.FromDays(29)))
                            {
                                // don't need to restore too young
                                // can't restore too old
                                continue;
                            }

                            Console.WriteLine("Restoring " + entry.PathDisplay);
                            var restored = await dropbox.Files.RestoreAsync(entry.PathLower, rev.Entries.First().Rev);

                            if (restored.AsFile.Size >= deletingBatchSize && filesToDelete.Count == 0)
                            {
                                Console.WriteLine("Deleting " + entry.PathDisplay);
                                await dropbox.Files.DeleteV2Async(restored.PathLower, restored.Rev);
                            }
                            else
                            {
                                // warning: rev not included, concurrent modification changes may be lost
                                filesToDelete.Add(restored.PathLower);
                                deletingAccumulatedSize += restored.Size;

                                if (deletingAccumulatedSize >= deletingBatchSize)
                                {
                                    await DeleteFilesBatchAsync();
                                }
                            }
                        }
                    }
                    await DeleteFilesBatchAsync();
                }

                Console.WriteLine("All done");
            }
            catch (Exception e)
            {
                // redirecting error to normal output
                Console.WriteLine(e);
                throw;
            }
        }
Пример #24
0
        public void Pack()
        {
            Common.Log(Environment.NewLine + "开始创建版本发布包...");

            //if (!ExcuteCmd(m_svnUpdateCmd))
            //{
            //    return;
            //}

            m_destPath = Path.Combine(m_packagePath, "ABSManager_" + m_newVersion);
            CheckFolderPath(m_destPath);

            if (!ModifyPubxml(m_newVersion, m_absManagementSitePath))
            {
                return;
            }

            if (!ModifyAssemblyInfo(m_oldVersion, m_newVersion,
                                    Path.Combine(m_gitPath, @"ChineseAbs.ABSManagement\Properties\AssemblyInfo.cs")))
            {
                return;
            }

            if (!ModifyAssemblyInfo(m_oldVersion, m_newVersion,
                                    Path.Combine(m_gitPath, @"ChineseAbs.ABSManagementSite\Properties\AssemblyInfo.cs")))
            {
                return;
            }

            Action <string, string> nugetPackage = (string packageConfigPath, string packagePath) => {
                var cdCmd    = "cd " + packageConfigPath;
                var nugetCmd = Path.Combine(m_gitPath, "../nuget.exe")
                               + " install -outputDirectory "
                               + Path.Combine(packageConfigPath, packagePath);

                if (!ExcuteCmd(cdCmd + Environment.NewLine + nugetCmd))
                {
                    return;
                }
            };

            nugetPackage(m_absManagementSitePath, Path.Combine(m_absManagementSitePath, "../packages"));

            var absManagementPath = m_absManagementSitePath.Replace("ChineseAbs.ABSManagementSite", "ChineseAbs.ABSManagement");

            nugetPackage(absManagementPath, Path.Combine(absManagementPath, "../packages"));

            var deploymentToolPath = m_absManagementSitePath.Replace("ChineseAbs.ABSManagementSite", "ChineseAbs.ABSManagement.DeploymentTool\\ABSMgrDeployment");

            nugetPackage(deploymentToolPath, Path.Combine(deploymentToolPath, "../packages"));

            var msBuild = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\msbuild";

            msBuild = "\"" + msBuild + "\"";

            var publishCmd = "set publishGitRootPath=";

            publishCmd += m_gitPath + Environment.NewLine;
            publishCmd += msBuild + @" %publishGitRootPath%\ChineseAbs.ABSManagementSite\ChineseAbs.ABSManagementSite.csproj"
                          + @" /p:Configuration=Release /p:DeployOnBuild=true "
                          + @"/p:PublishProfile=%publishGitRootPath%\ChineseAbs.ABSManagementSite\Properties\PublishProfiles\ABSManager.pubxml /p:VisualStudioVersion=12.0";
            if (!ExcuteCmd(publishCmd))
            {
                return;
            }

            var newVersionPath = m_versionPath + ' ' + m_newVersion;

            if (!CopyWebsiteFolder(newVersionPath, Path.Combine(m_destPath, "Website")))
            {
                return;
            }

            var destSqlPath = Path.Combine(m_destPath, "SQL");

            if (!Directory.Exists(destSqlPath))
            {
                Directory.CreateDirectory(destSqlPath);
            }
            if (!CopyWebsiteFolder(Path.Combine(m_gitPath, "ChineseAbs.ABSManagementSite/SQL"), destSqlPath))
            {
                return;
            }

            var buildCmd = "set publishGitRootPath=";

            buildCmd += m_gitPath + Environment.NewLine;
            buildCmd += "call " + "\"" + "%vs120comntools%vsvars32.bat" + "\"" + Environment.NewLine;
            buildCmd += "devenv " + @"%publishGitRootPath%\ChineseAbs.ABSManagement.DeploymentTool\ABSMgrDeployment.sln /Rebuild Release";

            if (!ExcuteCmd(buildCmd))
            {
                return;
            }

            if (!CopyDeploymentFiles(Path.Combine(m_absMgrDeploymentFilesPath, @"ABSMgrDeployment.exe"),
                                     Path.Combine(m_destPath, "ABSMgrDeployment.exe")))
            {
                return;
            }

            if (!CopyDeploymentFiles(Path.Combine(m_absMgrDeploymentFilesPath, "ABSMgrDeployment.exe.config"),
                                     Path.Combine(m_destPath, "ABSMgrDeployment.exe.config")))
            {
                return;
            }

            if (!CopyDeploymentFiles(Path.Combine(m_absMgrDeploymentFilesPath, "ICSharpCode.SharpZipLib.dll"),
                                     Path.Combine(m_destPath, "ICSharpCode.SharpZipLib.dll")))
            {
                return;
            }

            Common.Log("正在创建压缩包...");
            FastZip         zippy   = new FastZip();
            ZipEntryFactory factory = new ZipEntryFactory();

            factory.IsUnicodeText = true;
            zippy.EntryFactory    = factory;
            zippy.CreateZip("ABSManager_" + m_newVersion + ".zip", m_destPath, true, "");

            Common.Log("正在删除临时文件...");
            Directory.Delete(m_destPath, true);
            Common.Log("版本发布包创建成功" + Environment.NewLine);
        }
Пример #25
0
        public void Defaults()
        {
            var testStart = DateTime.Now;
            var f = new ZipEntryFactory();
            Assert.IsNotNull(f.NameTransform);
            Assert.AreEqual(-1, f.GetAttributes);
            Assert.AreEqual(0, f.SetAttributes);
            Assert.AreEqual(ZipEntryFactory.TimeSetting.LastWriteTime, f.Setting);

            Assert.LessOrEqual(testStart, f.FixedDateTime);
            Assert.GreaterOrEqual(DateTime.Now, f.FixedDateTime);

            f = new ZipEntryFactory(ZipEntryFactory.TimeSetting.LastAccessTimeUtc);
            Assert.IsNotNull(f.NameTransform);
            Assert.AreEqual(-1, f.GetAttributes);
            Assert.AreEqual(0, f.SetAttributes);
            Assert.AreEqual(ZipEntryFactory.TimeSetting.LastAccessTimeUtc, f.Setting);
            Assert.LessOrEqual(testStart, f.FixedDateTime);
            Assert.GreaterOrEqual(DateTime.Now, f.FixedDateTime);

            var fixedDate = new DateTime(1999, 1, 2);
            f = new ZipEntryFactory(fixedDate);
            Assert.IsNotNull(f.NameTransform);
            Assert.AreEqual(-1, f.GetAttributes);
            Assert.AreEqual(0, f.SetAttributes);
            Assert.AreEqual(ZipEntryFactory.TimeSetting.Fixed, f.Setting);
            Assert.AreEqual(fixedDate, f.FixedDateTime);
        }
Пример #26
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);
            }
        }
Пример #27
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);
                }
            }
        }
Пример #28
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);
        }
Пример #29
0
        private void ArchiveLogFiles(string prefix, IFileInfo[] logFileInfos)
        {
            string zipPath = Path.Combine(_logDir, $"Archived_{prefix}.zip");

            var archivedLogFileInfos = new List <IFileInfo>();

            try
            {
                if (_fileSystem.FileExists(zipPath))
                {
                    Dictionary <string, ZipEntry> zipEntries = GetZipEntries(zipPath)
                                                               .ToDictionary(x => x.Name);

                    IFileInfo[] logFilesNotInZip = logFileInfos
                                                   .Where(fileInfo =>
                    {
                        string name = Path.GetFileName(fileInfo.FullName);
                        ZipEntry existingZipEntry;
                        if (!zipEntries.TryGetValue(name, out existingZipEntry))
                        {
                            return(true);
                        }

                        if (existingZipEntry.Size != fileInfo.Length)
                        {
                            return(true);
                        }

                        double secondsDiff = Math.Abs(existingZipEntry.DateTime.Subtract(fileInfo.LastWriteTimeUtc).TotalSeconds);
                        if (secondsDiff > 2)
                        {
                            return(true);
                        }

                        return(false);
                    })
                                                   .ToArray();

                    if (!logFilesNotInZip.Any())
                    {
                        archivedLogFileInfos.AddRange(logFileInfos);
                    }
                    else
                    {
                        using (Stream stream = _fileSystem.GetStream(zipPath, FileMode.Open, FileAccess.ReadWrite))
                        {
                            var zipEntryFactory = new ZipEntryFactory(ZipEntryFactory.TimeSetting.Fixed);

                            var zipFile = new ZipFile(stream)
                            {
                                EntryFactory = zipEntryFactory
                            };

                            zipFile.BeginUpdate();

                            foreach (IFileInfo fileInfo in logFilesNotInZip)
                            {
                                Func <Stream> getStreamFunc =
                                    () => _fileSystem.GetStream(fileInfo.FullName, FileMode.Open, FileAccess.Read);

                                var staticDataSource = new FuncStreamStaticDataSource(getStreamFunc);

                                zipEntryFactory.FixedDateTime = fileInfo.LastWriteTimeUtc;
                                zipFile.Add(staticDataSource, Path.GetFileName(fileInfo.FullName));

                                archivedLogFileInfos.Add(fileInfo);
                            }

                            zipFile.CommitUpdate();
                        }
                    }
                }
                else
                {
                    using (Stream stream = _fileSystem.GetStream(zipPath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        using (var zipOutputStream = new ZipOutputStream(stream))
                        {
                            foreach (IFileInfo fileInfo in logFileInfos)
                            {
                                AddFileToZip(fileInfo, zipOutputStream);
                                archivedLogFileInfos.Add(fileInfo);
                            }
                        }
                    }
                }
            }
            catch
            {
                archivedLogFileInfos.Clear(); // Don't delete any file!

                if (_fileSystem.FileExists(zipPath))
                {
                    _fileSystem.DeleteFile(zipPath);
                }
            }

            DeleteFiles(archivedLogFileInfos);
        }
Пример #30
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);
        }