コード例 #1
0
ファイル: Zipper.cs プロジェクト: eitan-j/keysndr
 private void CreateFolders(ZipFile zip, bool hasView)
 {
     zip.AddDirectoryByName(KeySndrApp.ConfigurationsFolderName);
     zip.AddDirectoryByName(KeySndrApp.ScriptsFolderName);
     zip.AddDirectoryByName(KeySndrApp.MappingsFolderName);
     zip.AddDirectoryByName(KeySndrApp.MediaFolderName);
     if (hasView)
     {
         zip.AddDirectoryByName(KeySndrApp.ViewsFolderName);
     }
 }
コード例 #2
0
ファイル: EPUBGenerator.cs プロジェクト: rajeshwarn/PDFtoEPUB
        public static void GenerateEPUB(string inputFile, string outputFile, ConversionOptions options)
        {
            ZipFile file = new ZipFile(outputFile);

            //generate mimetype
            using (Stream mime = new MemoryStream())
            {
                byte[] mimeBytes = System.Text.Encoding.ASCII.GetBytes(_mimetype);
                mime.Write(mimeBytes, 0, mimeBytes.Length);
                file.AddEntry("mimetype", mime);
            }

            //generate META-INF
            file.AddDirectoryByName("META-INF");
            {
                //container.xml
                using (Stream container = new MemoryStream())
                {
                    byte[] containerBytes = System.Text.Encoding.ASCII.GetBytes(Crabwise.PDFtoEPUB.Properties.Resources.container);
                    container.Write(containerBytes, 0, containerBytes.Length);
                    file.AddEntry("META-INF\\container.xml", container);
                }
            }
            //generate OEBPS
            file.AddDirectoryByName("OEBPS");
            {
                //images
                file.AddDirectoryByName("OEBPS\\IMAGES");
                {
                    //add each image to the directory
                }

                //xhtml chapters


                //page-template.xpgt
                byte[] pagetemplateBytes = System.Text.Encoding.ASCII.GetBytes(Properties.Resources.page_template);
                file.AddEntry("OEBPS\\page-template.xpgt", pagetemplateBytes);

                //stylesheet.css
                byte[] stylesheetBytes = System.Text.Encoding.ASCII.GetBytes(Properties.Resources.stylesheet);
                file.AddEntry("OEBPS\\stylesheet.css", stylesheetBytes);

                //title_page.xhtml
                file.AddEntry("OEBPS\\title_page.xhtml", TitlePageGenerator.GetTitlePage(options));

                //Content.opf
                file.AddEntry("OEBPS\\content.opf", ContentFileGenerator.GetContentFile(options));

                //toc.ncx
                file.AddEntry("OEBPS\\toc.ncx", TOCFileGenerator.GetTOCFile(options));
            }
        }
コード例 #3
0
        private void addDirectory(DirectoryInfo sourceDir, DirectoryInfo rootSourceDir)
        {
            if (!flattenPaths)
            {
                string path = stripSourcePath(sourceDir.FullName, rootSourceDir);

                ZipEntry entry = zipFile.AddDirectoryByName(path);
                entry.AccessedTime = sourceDir.LastAccessTime;
                entry.Attributes   = sourceDir.Attributes;
                entry.CreationTime = sourceDir.CreationTime;
                entry.LastModified = sourceDir.LastWriteTime;
                entry.ModifiedTime = sourceDir.LastWriteTime;
            }
        }
コード例 #4
0
        private void zipFolder(CloudBlobClient blobClient, string basePrefix, string folderName, string zipDir, ref ZipFile zipFile)
        {
            zipDir = string.IsNullOrEmpty(zipDir) ? folderName : zipDir + "/" + folderName;
            zipFile.AddDirectoryByName(zipDir);
            var folderPrefix = basePrefix + StorageNamesEncoder.EncodeBlobName(folderName) + "/";

            var blobs = blobClient.ListBlobsWithPrefix(folderPrefix,
                                                       new BlobRequestOptions()
            {
                BlobListingDetails = Microsoft.WindowsAzure.StorageClient.BlobListingDetails.Metadata, UseFlatBlobListing = false
            });

            foreach (var blob in blobs)
            {
                if (blob is CloudBlobDirectory)
                {
                    var dir = blob as CloudBlobDirectory;

                    var names = dir.Uri.ToString().Split('/');
                    for (var i = names.Length - 1; i >= 0; i--)
                    {
                        if (!string.IsNullOrEmpty(names[i]))
                        {
                            zipFolder(blobClient, folderPrefix, StorageNamesEncoder.DecodeBlobName(names[i]), zipDir, ref zipFile);
                            break;
                        }
                    }
                }
                if (blob is CloudBlob)
                {
                    var cloudBlob = blob as CloudBlob;
                    var subStr    = cloudBlob.Uri.ToString().Substring(cloudBlob.Uri.ToString().IndexOf(folderPrefix) + folderPrefix.Length);
                    var index     = subStr.LastIndexOf('/');
                    if (index < 0)
                    {
                        index = 0;
                    }

                    var subFolderName = subStr.Substring(0, index);
                    var fileName      = subStr.Substring(index);
                    var bytes         = cloudBlob.DownloadByteArray();
                    if (!string.IsNullOrEmpty(subFolderName))
                    {
                        zipFile.AddDirectoryByName(zipDir + "/" + StorageNamesEncoder.DecodeBlobName(subFolderName));
                    }
                    zipFile.AddEntry(zipDir + "/" + StorageNamesEncoder.DecodeBlobName(subStr), bytes);
                }
            }
        }
コード例 #5
0
        public async Task <IActionResult> GetExport(int iMonat)
        {
            var contentRootPath = _env.ContentRootPath;

            using (ZipFile zip = new ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                zip.AddDirectoryByName("Files");


                //Set the Name of Zip File.
                string zipName      = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                var    memoryStream = new System.IO.MemoryStream();
                var    file         = System.IO.Path.Combine(contentRootPath, "MonthlyReposrt");
                AccountDto.ProcessWrite(_context, iMonat, file);
                zip.AddFile("MonthlyReposrt" + ".csv", "Files");

                using (var stream = new FileStream(file + ".csv", FileMode.Open))
                {
                    await stream.CopyToAsync(memoryStream);
                }

                //Save the Zip File to MemoryStream.
                zip.Save(memoryStream);

                memoryStream.Position = 0;
                return(NoContent());
            }
        }
コード例 #6
0
    protected void DownloadFiles(object sender, EventArgs e)
    {
        using (ZipFile zip = new ZipFile())
        {
            zip.AlternateEncodingUsage = ZipOption.AsNecessary;
            zip.AddDirectoryByName("EFT");
            LinkButton  btnButton = sender as LinkButton;
            GridViewRow gvRow     = (GridViewRow)btnButton.NamingContainer;
            System.Web.UI.WebControls.Label lblTitle = (System.Web.UI.WebControls.Label)gvRow.FindControl("lbl2");
            string    lblid = lblTitle.Text;
            DataTable dt    = Dbcon.Ora_Execute_table("select Fail_name from Settlement_batch where Batch_name='" + lblid + "'");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string filePath = Server.MapPath("~/FILES/SETGFILE/" + dt.Rows[i][0].ToString());
                    zip.AddFile(filePath, "Files");
                }


                Response.Clear();
                Response.BufferOutput = false;
                string zipName = String.Format("Zip_{0}.zip", lblid);
                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
                zip.Save(Response.OutputStream);
                Response.End();
            }
        }
    }
コード例 #7
0
ファイル: Mods.cs プロジェクト: xiuzhifu/Redirection
        private static void AddFolderToZip(ZipFile zipFile, string inputPath, string outputPath)
        {
            var directoryPaths = Directory.GetDirectories(inputPath);

            foreach (string directoryPath in directoryPaths)
            {
                if (!ShouldIgnoreDirectory(directoryPath))
                {
                    var directoryOutputPath = Path.Combine(outputPath, Path.GetFileName(directoryPath));
                    zipFile.AddDirectoryByName(directoryOutputPath);
                    AddFolderToZip(zipFile, directoryPath, directoryOutputPath);
                }
            }

            var filePaths = Directory.GetFiles(inputPath);

            foreach (string filePath in filePaths)
            {
                if (!ShouldIgnoreFile(filePath))
                {
                    var    fileOutputPath = Path.Combine(outputPath, Path.GetFileName(filePath));
                    byte[] contents       = File.ReadAllBytes(filePath);
                    zipFile.AddEntry(fileOutputPath, contents);
                }
            }
        }
コード例 #8
0
        public FileResult Zip()
        {
            string[]         filePaths = Directory.GetFiles(Server.MapPath("~/Files/"));
            List <FileModel> files     = new List <FileModel>();

            foreach (string filePath in filePaths)
            {
                files.Add(new FileModel()
                {
                    FileName = Path.GetFileName(filePath),
                    FilePath = filePath
                });
            }

            using (ZipFile zip = new ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                zip.AddDirectoryByName("Files");
                foreach (FileModel file in files)
                {
                    zip.AddFile(file.FilePath, "Files");
                }
                string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    zip.Save(memoryStream);
                    return(File(memoryStream.ToArray(), "application/zip", zipName));
                }
            }
        }
コード例 #9
0
        public async Task <IActionResult> GetExport()
        {
            var contentRootPath = _env.ContentRootPath;

            using (ZipFile zip = new ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                zip.AddDirectoryByName("Files");


                //Set the Name of Zip File.
                string zipName      = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                var    memoryStream = new MemoryStream();
                foreach (identifier val in Enum.GetValues(typeof(identifier)))
                {
                    var file = System.IO.Path.Combine(contentRootPath, val.ToString());
                    ProcessWrite(file);
                    zip.AddFile(val.ToString() + ".csv", "Files");

                    using (var stream = new FileStream(file + ".csv", FileMode.Open))
                    {
                        await stream.CopyToAsync(memoryStream);
                    }
                }

                //Save the Zip File to MemoryStream.
                zip.Save(memoryStream);

                memoryStream.Position = 0;
                return(File(memoryStream, System.Net.Mime.MediaTypeNames.Application.Octet, zipName));
            }
        }
コード例 #10
0
        public FileResult DownloadZip(string id)
        {
            int f_id                = Convert.ToInt32(id);
            var contributesList     = db.Contributions.Where(c => c.Student.FacultiesID == f_id);
            var selectedContributes = contributesList.Where(s => s.Status == "Selected" || s.Status == "Commented").ToList();

            List <FileModel> files = new List <FileModel>();

            foreach (var item in selectedContributes)
            {
                files.Add(new FileModel()
                {
                    FileName = item.Title,
                    FilePath = item.ArchiveLink
                });
            }

            using (ZipFile zip = new ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                zip.AddDirectoryByName("Files");
                foreach (FileModel file in files)
                {
                    zip.AddFile(file.FilePath, "Files");
                }
                string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    zip.Save(memoryStream);
                    return(File(memoryStream.ToArray(), "application/zip", zipName));
                }
            }
        }
コード例 #11
0
        //Download File
        public void DownLoadFiles(int? cmid)
        {
            cmid = 1016;
            var dir = new System.IO.DirectoryInfo(Server.MapPath("~/Content/Doc/" + cmid));
            System.IO.FileInfo[] fileNames = dir.GetFiles("*.*"); List<string> items = new List<string>();
            items.Add("");
            foreach (var file in fileNames)
            {
                items.Add(file.Name);
            }

            using (ZipFile zip = new ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;

                zip.AddDirectoryByName("Files");

                foreach (var file in fileNames)
                {
                    string filePath = Server.MapPath("~/Content/Doc/" + cmid + "/" + file.Name);
                    zip.AddFile(filePath, "Files");
                }

                Response.Clear();
                Response.BufferOutput = false;
                string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
                zip.Save(Response.OutputStream);
                Response.End();

            }


        }
コード例 #12
0
        private static void ProcessFileEntry(ProgramArgs args, PackageEntry packageConfigEntry, BuildConfigPackage buildConfigPackage,
                                             ZipFile zipFile)
        {
            var dirName = Path.GetDirectoryName(packageConfigEntry.GamePath);

            if (!string.IsNullOrWhiteSpace(dirName))
            {
                var newDirName = dirName;
                if (!newDirName.EndsWith("/"))
                {
                    newDirName += "/";
                }

                if (zipFile[newDirName] == null)
                {
                    zipFile.AddDirectoryByName(newDirName);
                }
            }

            var packageBasePath = Path.Combine(Path.GetDirectoryName(args.BuildConfigPath) ?? "", "src", buildConfigPackage.SourceName);
            var path            = Path.Combine(packageBasePath, packageConfigEntry.LocalPath);

            if (!File.Exists(path))
            {
                throw new Exception($"Package {buildConfigPackage.SourceName}: Directory {path} does not exist");
            }

            var data = File.ReadAllBytes(path);

            zipFile.AddEntry(packageConfigEntry.GamePath, data);
        }
コード例 #13
0
 public ActionResult DownloadZipFile(int ideaCateId)
 {
     if (new IdeaCategoryDao().ChkFinaGtThanNow(ideaCateId / 777) == false)
     {
         List <Idea> files    = new IdeaDao().GetLFSPOverDateByCateId(ideaCateId / 777);
         string      basePath = AppDomain.CurrentDomain.BaseDirectory;
         //string fileName = path.Substring(path.LastIndexOf('/') + 1);
         if (files.Count > 0)
         {
             using (ZipFile zip = new ZipFile())
             {
                 zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                 zip.AddDirectoryByName("Files");
                 foreach (var item in files)
                 {
                     zip.AddFile(basePath + item.FileSP.Replace("~", ""), "Files");
                 }
                 string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MM-dd"));
                 using (MemoryStream memoryStream = new MemoryStream())
                 {
                     zip.Save(memoryStream);
                     return(File(memoryStream.ToArray(), "application/zip", zipName));
                 }
             }
         }
         else
         {
             return(RedirectToAction("Index/" + (int)TempData["grID"]));
         }
     }
     else
     {
         return(null);
     }
 }
コード例 #14
0
        protected void btnDownload_Click(object sender, EventArgs e)
        {
            //string finalpath = Session["finalpath"].ToString();
            //string filenamestr = System.Web.HttpContext.Current.Session["varName"].ToString();
            //string filenameinfographicstr = System.Web.HttpContext.Current.Session["varNameinfographic"].ToString();
            //string filenameexecutivestr = System.Web.HttpContext.Current.Session["varNameexecutive"].ToString();
            //string filenameekeymetricsstr = System.Web.HttpContext.Current.Session["varNameKeyMetrics"].ToString();

            using (ZipFile zip = new ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                zip.AddDirectoryByName("surveypdf1");
                zip.AddFile(finalpath + filenamestr + ".pdf");
                zip.AddFile(finalpath + filenameinfographicstr + ".pdf", "surveypdf1");
                zip.AddFile(finalpath + filenameexecutivestr + ".pdf", "surveypdf1");
                //zip.AddFile(finalpath + filenameekeymetricsstr + ".pdf", "surveypdf1");

                Response.Clear();
                Response.BufferOutput = false;
                //string zipName = String.Format("Practice Performance Assessment{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                string zipName = "PracticePerformanceAssessment_" + Username + "_" + DateTime.Now.ToString("MM/dd/yyyy") + ".zip";
                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
                zip.Save(Response.OutputStream);
                //Response.End();
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
        }
コード例 #15
0
        static void createPathsInZip(string dir)
        {
            string dirString = "";

            try
            {
                string[] dirArgs = splitString(dir, @"\");
                for (int i = 0; i <= dirArgs.Length; i++)
                {
                    for (int x = 0; x < i; x++)
                    {
                        if (x < i - 1)
                        {
                            dirString += dirArgs[x] + @"\";
                        }
                        else
                        {
                            dirString += dirArgs[x];
                        }
                    }
                    if (!createdDirectories.Contains(dirString) && !dirString.Equals(""))
                    {
                        G.print("Adding directory " + dir + " subdirectory " + dirString);
                        createdDirectories.Add(dirString);
                        zip.AddDirectoryByName(dirString);
                    }
                    dirString = "";
                }
            }
            catch (Exception ex)
            {
                G.print("Error when creating directory path " + dir + " subdirectory " + dirString + " in zip");
                dirString = "";
            }
        }
コード例 #16
0
ファイル: FileUtils.cs プロジェクト: pasamsin/SolidCP
        /*** CreateBackupZip
         * params:
         * zipFile: Destination file of zipped backup
         * rootpath: Path of Folder to Backup Example: C:\HostingSpace\243423
         *
         * Creates a zipped backup of Folder rootPath, excluding .wspak or .scpak Backup Files
         * */
        public static void CreateBackupZip(string zipFile, string rootpath)
        {
            using (ZipFile zip = new ZipFile())
            {
                //use unicode if necessary
                zip.UseUnicodeAsNecessary = true;
                zip.UseZip64WhenSaving    = Zip64Option.AsNecessary;

                //skip locked files
                zip.ZipErrorAction = ZipErrorAction.Skip;
                string[] zipfiles = BackupFileNames(rootpath, "").ToArray();
                foreach (string file in zipfiles)
                {
                    string fullPath = Path.Combine(rootpath, file);
                    if (Directory.Exists(fullPath))
                    {
                        //add empty Directory
                        zip.AddDirectoryByName(file);
                    }
                    else if (File.Exists(fullPath))
                    {
                        string path = "";
                        try
                        {
                            int idx = file.LastIndexOf("\\");
                            path = file.Substring(0, idx);
                        }
                        catch { }
                        //add file to relative folder
                        zip.AddFile(fullPath, path);
                    }
                }
                zip.Save(zipFile);
            }
        }
コード例 #17
0
ファイル: FileLogManager.cs プロジェクト: ilkerogutcu/logger
        public async Task <FileContentResultModel> GetLogFilesByDateRange(DateTime startDate, DateTime endDate)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            using var iterator = Utilities.GetDateRange(startDate, endDate).GetEnumerator();

            using var zip = new ZipFile { AlternateEncodingUsage = ZipOption.AsNecessary };

            var filePaths = Directory.GetFiles(GetFilePath()).ToList();

            zip.AddDirectoryByName("Files");

            while (iterator.MoveNext())
            {
                var item  = iterator.Current.ToString("yyyy-MM-dd");
                var files = filePaths.FindAll(x => x.EndsWith(item + ".txt"));
                if (files.Count > 0)
                {
                    files.ForEach(x => zip.AddFile($"{x}", "Files"));
                }
            }

            var zipName = $"Zip_{DateTime.Now:yyyy-MMM-dd-HHmmss}.zip";

            await using var memoryStream = new MemoryStream();
            zip.Save(memoryStream);

            return(new FileContentResultModel
            {
                FileContents = memoryStream.ToArray(),
                ContentType = "application/zip",
                FileDownloadName = zipName
            });
        }
コード例 #18
0
        protected void lnkBtnDownload_OnClick(object sender, EventArgs e)
        {
            using (var zip = new ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                zip.AddDirectoryByName("EPGXmls");

                foreach (var dataKey in from GridViewRow row in gvFiles.Rows
                         where row.RowType == DataControlRowType.DataRow
                         where ((CheckBox)row.FindControl("chkSelect")).Checked
                         select Convert.ToString(gvFiles.DataKeys[row.RowIndex]["URL"])
                         into dataKey
                         where File.Exists(Server.MapPath(dataKey))
                         select dataKey)
                {
                    var filePath = Server.MapPath(dataKey);
                    zip.AddFile(filePath, "EPGXmls");
                }

                if (zip.Count <= 0)
                {
                    return;
                }
                Response.Clear();
                Response.BufferOutput = false;
                var zipName = String.Format("EPGXmls_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
                zip.Save(Response.OutputStream);
                Response.End();
            }
        }
コード例 #19
0
        public void DownLoadPhoto(int id)
        {
            List <Photo> ObjPhotos = GetPhotoListSeance(id);

            using (ZipFile zip = new ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                zip.AddDirectoryByName("Photos");

                //var PhotoBySeanceId = (from p in ObjPhotos
                //                       where p.Seance_ID.Equals(id)
                //                       select new { p.Nom, p.Photo1 }).ToList();
                string contentType = "image/jpg";
                int    NB          = 0;
                foreach (var p in ObjPhotos)
                {
                    NB++;
                    zip.AddEntry("Photos/" + p.Nom + NB + ".jpg", p.Photo1);
                }
                Response.Clear();
                Response.BufferOutput = false;
                string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
                zip.Save(Response.OutputStream);
                Response.End();
            }
        }
コード例 #20
0
        protected void btn_Click(object sender, EventArgs e)
        {
            using (ZipFile zip = new ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                zip.AddDirectoryByName("Files");


                foreach (GridViewRow row in GridView1.Rows)
                {
                    //if ((row.FindControl("chkSelect") as CheckBox).Checked)
                    //{
                    //string filePath = (row.FindControl("lblFilePath") as Label).Text;
                    //zip.AddFile(filePath, "Files");
                    //}
                }
                Response.Clear();
                Response.BufferOutput = false;
                string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
                zip.Save(Response.OutputStream);
                Response.End();
            }
        }
コード例 #21
0
 protected void btnDownloadDocument_Click(object sender, EventArgs e)
 {
     using (ZipFile zip = new ZipFile())
     {
         zip.AlternateEncodingUsage = ZipOption.AsNecessary;
         zip.AddDirectoryByName("SolicitorDoc");
         dsDocSubmittedtoSolicitor = dbFamilyDetailsData.getHOSolicitDocumentSubmitted(cmbVillage.SelectedValue.ToString(), cmbDocumentNo.SelectedValue.ToString());
         if (dsDocSubmittedtoSolicitor.Tables[0].Rows.Count > 0)
         {
             foreach (DataRow rows in dsDocSubmittedtoSolicitor.Tables[0].Rows)
             {
                 string DocFileName = rows["documentname"].ToString();
                 if (DocFileName != "" && !string.IsNullOrEmpty(DocFileName))
                 {
                     string FileExist = Server.MapPath(@"~/Documents/" + cmbVillage.SelectedValue.ToString() + "/" + DocFileName);
                     if (File.Exists(FileExist))
                     {
                         zip.AddFile(FileExist, "SolicitorDoc");
                     }
                 }
             }
         }
         Response.Clear();
         Response.BufferOutput = false;
         string zipName = String.Format("Solicitor_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
         Response.ContentType = "application/zip";
         Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
         zip.Save(Response.OutputStream);
         Response.End();
     }
 }
コード例 #22
0
ファイル: ErrorTests.cs プロジェクト: Belxjander/Asuna
 public void CreateZip_AddDirectory_BlankName()
 {
     string zipFileToCreate = Path.Combine(TopLevelDir, "CreateZip_AddDirectory_BlankName.zip");
     using (ZipFile zip = new ZipFile(zipFileToCreate))
     {
         zip.AddDirectoryByName("");
         zip.Save();
     }
 }
コード例 #23
0
        /// <summary>
        /// Save this PXZ file to disk
        /// </summary>
        /// <param name="path">The file to save to/create</param>
        public void Save(string path)
        {
            //delete the existing file (if it exists)
            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }

            //new index attributes (don't override records though)
            FileIndex.Author = PxzAuthor.FromCurrent();

            var idxDoc = FileIndex.ToXml();

            //deflate the content to save room (poster isn't compressed via Zlib)
            var idxByte = GZipCompressor.CompressString(idxDoc.OuterXml);

            //names of root format items
            const string idxName = @"index";
            const string recName = @"records";

            //create a new temporary Zip file (in memory, not on disk)
            using var archive = new ZipFile(path, Encoding.Default);

            //add the indexing information to the PXZ
            archive.AddEntry(idxName, idxByte);

            //add records folder
            archive.AddDirectoryByName(recName);

            //traverse the records list
            foreach (var r in Records)
            {
                //null records are skipped
                if (r == null)
                {
                    continue;
                }

                //convert to record string
                var raw = r.ToRawForm();

                //record name
                var fileName = $"{recName}/{r.Header.Naming.StoredName}";

                //add the ZIP entry of the file
                if (!archive.Any(entry => entry.FileName.EndsWith(fileName)))
                {
                    archive.AddEntry(fileName, raw);
                }
            }

            //finalise ZIP file
            archive.Save(path);

            //cull the residual archive from memory
            archive.Dispose();
        }
コード例 #24
0
ファイル: EpubBase.cs プロジェクト: sashaMilka/MultiReader
 protected void BuildEpubStructure()
 {
     file = new ZipFile();
     file.AddEntry("mimetype", Resources.Mimetype).CompressionLevel = CompressionLevel.None;
     if (!string.IsNullOrEmpty(Structure.Directories.ContentFolder))
     {
         file.AddDirectoryByName(Structure.Directories.ContentFolder);
     }
     file.AddDirectoryByName(Structure.Directories.MetaInfFolder);
     if (!string.IsNullOrEmpty(Structure.Directories.ImageFolder))
     {
         file.AddDirectoryByName(Structure.Directories.ImageFolderFullPath);
     }
     if (!string.IsNullOrEmpty(Structure.Directories.CssFolder))
     {
         file.AddDirectoryByName(Structure.Directories.CssFolderFullPath);
     }
 }
コード例 #25
0
        public ActionResult Resign(string email, string name, string phone)
        {
            try
            {
                var obj = new Resignation
                {
                    Email       = email,
                    Phone       = phone,
                    Name        = name,
                    CreatedDate = DateTime.Now
                };
                var result     = _resignService.Add(obj);
                var FolderPath = System.Web.HttpContext.Current.Request.MapPath(string.Format("/BangGia"));

                //Define file Type
                string fileType = "application/octet-stream";

                //Define Output Memory Stream
                var outputStream = new MemoryStream();

                //Create object of ZipFile library
                using (ZipFile zipFile = new ZipFile())
                {
                    //Add Root Directory Name "Files" or Any string name
                    zipFile.AddDirectoryByName("Files");

                    //Get all filepath from folder
                    String[] files = Directory.GetFiles(FolderPath);
                    foreach (string file in files)
                    {
                        string filePath = file;
                        //Adding files from filepath into Zip
                        zipFile.AddFile(filePath, "Files");
                    }

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

                    //Set zip file name
                    Response.AppendHeader("content-disposition", "attachment; filename=BangGia.zip");

                    //Save the zip content in output stream
                    zipFile.Save(outputStream);
                }

                //Set the cursor to start position
                outputStream.Position = 0;

                //Dispance the stream
                return(new FileStreamResult(outputStream, fileType));
            }
            catch (Exception ex)
            {
                OutputLog.WriteOutputLog(ex);
                throw;
            }
        }
コード例 #26
0
        internal DNZSAZWriter(string sFilename)
        {
            _sFilename = sFilename;
            _oZip      = new ZipFile(sFilename);

            // Create the directory explicitly (not strictly required) because this matches
            // legacy behavior and some code checks for it.
            _oZip.AddDirectoryByName("raw");
        }
コード例 #27
0
        public void CreateZip_AddDirectory_BlankName()
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, "CreateZip_AddDirectory_BlankName.zip");

            using (ZipFile zip = new ZipFile(zipFileToCreate))
            {
                zip.AddDirectoryByName("");
                zip.Save();
            }
        }
コード例 #28
0
        public HttpResponseMessage getzipIDFC()
        {
            //using (ZipFile zip = new ZipFile())  [FromBody] ZipDownload data
            //{
            //    zip.AddDirectory("C:/Users/Rishabh/Pictures/Saved Pictures/");

            //    MemoryStream output = new MemoryStream();
            //    zip.Save(output);
            //   // return File(output, "application/zip", "sample.zip");
            //}

            //Create HTTP Response.
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

            string[] url = { "E:/vscode angular/QuickcheckApi/QuickZipWebAPI/Images/CHKrDLa.jpg", "E:/vscode angular/QuickcheckApi/QuickZipWebAPI/Images/LW8EKdK.jpg" };
            //Create the Zip File.
            using (ZipFile zip = new ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                zip.AddDirectoryByName("Files");
                //foreach (FileModel file in files)
                //{
                //    if (file.IsSelected)
                //    {
                for (int i = 0; i < url.Length; i++)
                {
                    zip.AddFile(url[i], "Files");
                }
                //    }
                //}

                //Set the Name of Zip File.
                string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    //Save the Zip File to MemoryStream.
                    zip.Save(memoryStream);

                    //Set the Response Content.
                    response.Content = new ByteArrayContent(memoryStream.ToArray());

                    //Set the Response Content Length.
                    response.Content.Headers.ContentLength = memoryStream.ToArray().LongLength;

                    //Set the Content Disposition Header Value and FileName.
                    response.Content.Headers.ContentDisposition          = new ContentDispositionHeaderValue("attachment");
                    response.Content.Headers.ContentDisposition.FileName = zipName;

                    //Set the File Content Type.
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
                    return(response);
                }
            }
        }
コード例 #29
0
ファイル: ErrorTests.cs プロジェクト: syrompetka/mudclient
        public void CreateZip_AddDirectory_BlankName()
        {
            string ZipFileToCreate = Path.Combine(TopLevelDir, "CreateZip_AddDirectory_BlankName.zip");

            Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate);
            using (ZipFile zip = new ZipFile(ZipFileToCreate))
            {
                zip.AddDirectoryByName("");
                zip.Save();
            }
        }
コード例 #30
0
 public ActionResult Download_CR_Tracker_Files_In_Zip(int crID)
 {
     try
     {
         string       whereCondition = "CR_ID = " + crID + "";
         SqlParameter param          = new SqlParameter(parameterName: "@WhereQuery", value: string.IsNullOrEmpty(whereCondition) ? Convert.DBNull : whereCondition);
         DataTable    cr_file_dt     = Shared.DbHelper.GetDataTableWithParameterArraySql(Get_Connection_String(), "sp_Download_Files_In_Zip", param);
         if (cr_file_dt != null && cr_file_dt.Rows.Count > 0)
         {
             //convert datatable to onject list
             List <FileModel> files = new List <FileModel>();
             //string[] filePaths = Directory.GetFiles(Server.MapPath("~/CR_Tracker_Files/"));
             foreach (DataRow row in cr_file_dt.Rows)
             {
                 string filePath = Server.MapPath("~/CR_Tracker_Files/" + row["FileName"].ToString());
                 if (System.IO.File.Exists(filePath))
                 {
                     files.Add(new FileModel()
                     {
                         FileName   = Path.GetFileName(filePath),
                         FilePath   = filePath,
                         IsSelected = true
                     });
                 }
             }
             using (ZipFile zip = new ZipFile())
             {
                 zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                 zip.AddDirectoryByName("Files");
                 foreach (FileModel file in files)
                 {
                     if (file.IsSelected)
                     {
                         zip.AddFile(file.FilePath, "Files");
                     }
                 }
                 string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                 using (MemoryStream memoryStream = new MemoryStream())
                 {
                     zip.Save(memoryStream);
                     return(File(memoryStream.ToArray(), "application/zip", zipName));
                 }
             }
         }
         return(RedirectToAction("CR_Tracker_Dashboard"));
     }
     catch (Exception ex)
     {
         ViewBag.Error_Message = ex.Message.ToString();
         return(RedirectToAction("CR_Tracker_Dashboard"));
     }
 }
コード例 #31
0
        internal DNZSAZWriter(string sFilename)
        {
            _sFilename = sFilename;
            _oZip      = new ZipFile(sFilename);

            // We may need to use Zip64 format if the user saves more than 21844 sessions, because
            // each session writes 3 files and the non-Zip64 format is limited to 65535 files.
            _oZip.UseZip64WhenSaving = Zip64Option.AsNecessary;

            // Create the directory explicitly (not strictly required) because this matches
            // legacy behavior and some code checks for it.
            _oZip.AddDirectoryByName("raw");
        }
コード例 #32
0
ファイル: Form1.cs プロジェクト: ChrisPaine/C-sharp
 private void button1_Click(object sender, EventArgs e)
 {
     OpenFileDialog ofd = new OpenFileDialog();
     FolderBrowserDialog fbd = new FolderBrowserDialog();
     if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         ZipFile zf = new ZipFile("C:\\Users\\cpaine\\Desktop\\MyZipFile.zip");
         zf.AddDirectoryByName("Adam");
         zf.AddFile(ofd.FileName, "Adam");
         //zf.AddDirectory(fbd.SelectedPath, "");
         if.Save;
     }
 }
コード例 #33
0
ファイル: ZipLibTests.cs プロジェクト: xeno-by/datavault
        public void MainSuccessScenario()
        {
            var content1 = "content1 " + Guid.NewGuid();
            var content2 = "content2 " + Guid.NewGuid();

            using (var write = new ZipFile())
            {
                write.AddFileFromString("file1.txt", "", content1);
                write.AddFileFromString("file2.txt", @"Dir1\Dir2\", content2);
                write.AddDirectoryByName("Dir2/Dir3");
                write.Save("testarc.zip");
                write.Dispose();
            }

            using(var read = new ZipFile("testarc.zip"))
            {
                Assert.AreEqual(1, read.Entries.Where(e => e.IsDirectory).Count());
                Assert.AreEqual(2, read.Entries.Where(e => !e.IsDirectory).Count());

                var ms1 = new MemoryStream();
                var ms2 = new MemoryStream();
                read.Extract(@"file1.txt", ms1);
                read.Extract(@"Dir1\Dir2\file2.txt", ms2);
                ms1.Seek(0, SeekOrigin.Begin);
                ms2.Seek(0, SeekOrigin.Begin);
                read.Dispose();

                Assert.AreEqual(content1, new StreamReader(ms1).ReadToEnd());
                Assert.AreEqual(content2, new StreamReader(ms2).ReadToEnd());
            }

            using (var write2 = new ZipFile("testarc.zip"))
            {
                write2.RemoveEntry(@"file1.txt");
                write2.Save();
                write2.Dispose();
            }

            using (var read2 = new ZipFile("testarc.zip"))
            {
                Assert.AreEqual(1, read2.Entries.Where(e => !e.IsDirectory).Count());
                Assert.AreEqual(1, read2.Entries.Where(e => e.IsDirectory).Count());
            }
        }
コード例 #34
0
        public void Password_UnsetEncryptionAfterSetPassword_wi13909_ZF()
        {
            // Verify that unsetting the Encryption property after
            // setting a Password results in no encryption being used.
            // This method tests ZipFile.
            string unusedPassword = TestUtilities.GenerateRandomPassword();
            int numTotalEntries = _rnd.Next(46)+653;
            string zipFileToCreate = "UnsetEncryption.zip";

            using (var zip = new ZipFile())
            {
                zip.Password = unusedPassword;
                zip.Encryption = EncryptionAlgorithm.None;

                for (int i=0; i < numTotalEntries; i++)
                {
                    if (_rnd.Next(7)==0)
                    {
                        string entryName = String.Format("{0:D5}", i);
                        zip.AddDirectoryByName(entryName);
                    }
                    else
                    {
                        string entryName = String.Format("{0:D5}.txt", i);
                        if (_rnd.Next(12)==0)
                        {
                            var block = TestUtilities.GenerateRandomAsciiString() + " ";
                            string contentBuffer = String.Format("This is the content for entry {0}", i);
                                int n = _rnd.Next(6) + 2;
                                for (int j=0; j < n; j++)
                                    contentBuffer += block;
                            byte[] buffer = System.Text.Encoding.ASCII.GetBytes(contentBuffer);
                            zip.AddEntry(entryName, contentBuffer);
                        }
                        else
                            zip.AddEntry(entryName, Stream.Null);
                    }
                }
                zip.Save(zipFileToCreate);
            }

            BasicVerifyZip(zipFileToCreate);
        }
コード例 #35
0
ファイル: ZipVault.cs プロジェクト: xeno-by/datavault
        private void SaveImpl(String fileName, bool rebuildZipEntries)
        {
            using (ExposeReadOnly())
            {
                var newzip = new ZipFile(){Encoding = Encoding.UTF8};

                // bug. here we face a potential tho very unprobable sync problem
                // if we've imported some nodes from another vault and are now unbinding them
                // it's possible that the vault will right now undergo certain changes that
                // won't be propagated to the nodes we've just unbound
                Root.GetValuesRecursive(ValueKind.RegularAndInternal).ForEach(Bind);
                Root.GetBranchesRecursive().ForEach(Bind);

                // mapping between values/branches and entries in the new file
                var newZeIndex = new Dictionary<IElement, String>();

                // save all values -> this will also automatically create corresponding branches
                foreach (Value value in Root.GetValuesRecursive(ValueKind.RegularAndInternal))
                {
                    var contentStream = value.ContentStream.FixupForBeingSaved();
                    var valueZe = newzip.AddFileStream(value.Name, value.VPath.Parent.ToZipPathDir(), contentStream);
                    newZeIndex.Add(value, valueZe.FileName);

                    if (value.Metadata.Raw != null)
                        newzip.AddFileStream(value.Name + "$", value.VPath.Parent.ToZipPathDir(), value.Metadata.Raw.AsStream());
                }

                // despite of the previous step having created the branches, 
                // we still need to explicitly add them in order to store the metadata
                foreach(Branch branch in Root.GetBranchesRecursive())
                {
                    var branchZe = newzip.AddDirectoryByName(branch.VPath.ToZipPathDir());
                    newZeIndex.Add(branch, branchZe.FileName);

                    if (branch.Metadata.Raw != null)
                        newzip.AddFileStream("$", branch.VPath.ToZipPathDir(), branch.Metadata.Raw.AsStream());
                }

                // root metadata requires special treatment since root doesn't get enumerated
                if (Root.Metadata.Raw.IsNeitherNullNorEmpty())
                    newzip.AddFileStream("$", String.Empty.ToZipPathDir(), Root.Metadata.Raw.AsStream());

                if (rebuildZipEntries)
                {
                    GC.Collect(); // is this really necessary here?
                    var deletedButStillAlive = BoundElements.Select(wr => wr.IsAlive ? (IElement)wr.Target : null)
                        .Where(el => el != null)
                        .Except(Root.GetValuesRecursive(ValueKind.RegularAndInternal).Cast<IElement>())
                        .Except(Root.GetBranchesRecursive().Cast<IElement>())
                        .Except(Root.MkArray())
                        .Distinct();

                    // fixup metadata/content streams of deleted and not yet gcollected nodes
                    Action<Action> neverFail = a => { try { a(); } catch { /* just ignore */ } };
                    deletedButStillAlive.ForEach(el => neverFail(() => el.CacheInMemory()));

                    // only now can we dispose the previous zip instance
                    // previously it was necessary to extract streams we're going to repack
                    if (Zip != null)
                    {
                        Zip.Dispose();
                    }

                    Zip = newzip;
                    newzip.Save(fileName);

                    // fixup content/metadata streams to reference the new file/vpaths
                    var opt = Zip.Entries.ToDictionary(ze => ze.FileName, ze => ze);
                    foreach (Value value in Root.GetValuesRecursive(ValueKind.RegularAndInternal))
                    {
                        var contentFile = newZeIndex[value];
                        var metadataFile = contentFile + "$";

                        value.SetContent(() => opt[contentFile].ExtractEager());
                        value.RawSetMetadata(() => opt.GetOrDefault(metadataFile).ExtractEager());
                    }

                    foreach (Branch branch in Root.GetBranchesRecursive())
                    {
                        var metadataFile = newZeIndex[branch] + "$";
                        branch.RawSetMetadata(() => opt.GetOrDefault(metadataFile).ExtractEager());
                    }

                    // root metadata requires special treatment since root doesn't get enumerated
                    Root.RawSetMetadata(() => (opt.GetOrDefault("/$") ?? opt.GetOrDefault("$")).ExtractEager());

                    // set the changes in stone
                    Root.AfterSave();
                    Root.GetBranchesRecursive().Cast<Branch>().ForEach(b => b.AfterSave());
                    Root.GetValuesRecursive(ValueKind.RegularAndInternal).Cast<Value>().ForEach(v => v.AfterSave());
                }
                else
                {
                    if (Uri == fileName)
                    {
                        throw new InvalidOperationException("Saving vault into its source file requires rebuilding ZIP entries.");
                    }
                    else
                    {
                        newzip.Save(fileName);
                        newzip.Dispose();
                    }
                }
            }
        }