Exemple #1
0
        /** Deserializes graph editor settings.
         * For future compatibility this method does not assume that the \a graphEditors array matches the #graphs array in order and/or count.
         * It searches for a matching graph (matching if graphEditor.target == graph) for every graph editor.
         * Multiple graph editors should not refer to the same graph.\n
         * \note Stored in files named "graph#_editor.json" where # is the graph number.
         */
        public void DeserializeEditorSettings(GraphEditorBase[] graphEditors)
        {
            if (graphEditors == null)
            {
                return;
            }

            for (int i = 0; i < graphEditors.Length; i++)
            {
                if (graphEditors[i] == null)
                {
                    continue;
                }
                for (int j = 0; j < graphs.Length; j++)
                {
                    if (graphEditors[i].target != graphs[j])
                    {
                        continue;
                    }

                    var      zipIndex = graphIndexInZip[graphs[j]];
                    ZipEntry entry    = GetEntry("graph" + zipIndex + "_editor" + jsonExt);
                    if (entry == null)
                    {
                        continue;
                    }

                    TinyJsonDeserializer.Deserialize(GetString(entry), graphEditors[i].GetType(), graphEditors[i]);
                    break;
                }
            }
        }
        /// <summary> 压缩数据 </summary>
        public static byte[] Compress(byte[] source)
        {
#if false//SCORPIO_UWP && !UNITY_EDITOR
            using (MemoryStream stream = new MemoryStream()) {
                System.IO.Compression.ZipArchive      zipStream = new System.IO.Compression.ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Create);
                System.IO.Compression.ZipArchiveEntry zipEntry  = zipStream.CreateEntry("0.txt");
                Stream entryStream = zipEntry.Open();
                entryStream.Write(source, 0, source.Length);
                entryStream.Flush();
                entryStream.Dispose();
                zipStream.Dispose();
                byte[] ret = stream.ToArray();
                stream.Dispose();
                return(ret);
            }
#else
            using (MemoryStream stream = new MemoryStream()) {
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream);
                zipStream.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry("0.txt"));
                zipStream.Write(source, 0, source.Length);
                zipStream.Finish();
                byte[] ret = stream.ToArray();
                zipStream.Dispose();
                stream.Dispose();
                return(ret);
            }
#endif
        }
Exemple #3
0
        public bool WriteFile(string filename)
        {
            StreamWriter sw = null;

            FolderPath = Path.GetDirectoryName(filename);
            FileName   = filename;
            if (filename.EndsWith("xml"))
            {
                WriteXMLFile(filename);
                return(true);
            }
#if (IFCJSON)
            else if (filename.EndsWith("json"))
            {
                WriteJSONFile(filename);
                return(true);
            }
#endif
#if (!NOIFCZIP)
            bool zip = filename.EndsWith(".ifczip");
            System.IO.Compression.ZipArchive za = null;
            if (zip)
            {
                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);
                }
                za = System.IO.Compression.ZipFile.Open(filename, System.IO.Compression.ZipArchiveMode.Create);
                System.IO.Compression.ZipArchiveEntry zae = za.CreateEntry(System.IO.Path.GetFileNameWithoutExtension(filename) + ".ifc");
                sw = new StreamWriter(zae.Open());
            }
            else
#endif
            sw = new StreamWriter(filename);
            CultureInfo current = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            sw.Write(getHeaderString(filename) + "\r\n");
            for (int icounter = 1; icounter < mIfcObjects.Count; icounter++)
            {
                BaseClassIfc ie = mIfcObjects[icounter];
                if (ie != null)
                {
                    string str = ie.ToString();
                    if (!string.IsNullOrEmpty(str))
                    {
                        sw.WriteLine(str);
                    }
                }
            }
            sw.Write(getFooterString());
            sw.Close();
            Thread.CurrentThread.CurrentUICulture = current;
#if (!NOIFCZIP)
            if (zip)
            {
                za.Dispose();
            }
#endif
            return(true);
        }
        private GraphMeta DeserializeBinaryMeta(ZipEntry entry)
        {
            var meta = new GraphMeta();

            var reader = GetBinaryReader(entry);

            if (reader.ReadString() != "A*")
            {
                throw new System.Exception("Invalid magic number in saved data");
            }
            int major    = reader.ReadInt32();
            int minor    = reader.ReadInt32();
            int build    = reader.ReadInt32();
            int revision = reader.ReadInt32();

            // Required because when saving a version with a field not set, it will save it as -1
            // and then the Version constructor will throw an exception (which we do not want)
            if (major < 0)
            {
                meta.version = new Version(0, 0);
            }
            else if (minor < 0)
            {
                meta.version = new Version(major, 0);
            }
            else if (build < 0)
            {
                meta.version = new Version(major, minor);
            }
            else if (revision < 0)
            {
                meta.version = new Version(major, minor, build);
            }
            else
            {
                meta.version = new Version(major, minor, build, revision);
            }

            meta.graphs = reader.ReadInt32();

            meta.guids = new List <string>();
            int count = reader.ReadInt32();

            for (int i = 0; i < count; i++)
            {
                meta.guids.Add(reader.ReadString());
            }

            meta.typeNames = new List <string>();
            count          = reader.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                meta.typeNames.Add(reader.ReadString());
            }
            reader.Close();

            return(meta);
        }
Exemple #5
0
 public BclZipEntry(System.IO.Compression.ZipArchiveEntry entry)
 {
     CompressedLength   = entry.CompressedLength;
     ExternalAttributes = entry.ExternalAttributes;
     FullName           = entry.FullName;
     LastWriteTime      = entry.LastWriteTime;
     Length             = entry.Length;
     Name = entry.Name;
 }
        public IActionResult Get()
        {
            List <string> fileName = new List <string>();

            fileName.Add("00937dc9a02547cd95e17bf7f992f957.txt");
            fileName.Add("025ce8e69d3640c498a653a43a0428dc.jpg");

            List <SourceFile> sourceFiles = new List <SourceFile>();

            foreach (var fname in fileName)
            {
                string[]       fdata      = fname.Split(".");
                CloudBlockBlob blockBlob  = GetBlockBlobDetail(fname);
                Stream         blobStream = blockBlob.OpenReadAsync().GetAwaiter().GetResult();
                sourceFiles.Add(new SourceFile()
                {
                    Name = fdata[0], Extension = fdata[1], FileBytes = ReadFully(blobStream)
                });
            }
            // get the source files

            // ...

            // the output bytes of the zip
            byte[] fileBytes = null;

            // create a working memory stream
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                // create a zip
                using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
                {
                    // interate through the source files
                    foreach (SourceFile f in sourceFiles)
                    {
                        // add the item name to the zip
                        System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(f.Name + "." + f.Extension);
                        // add the item bytes to the zip entry by opening the original file and copying the bytes
                        using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(f.FileBytes))
                        {
                            using (System.IO.Stream entryStream = zipItem.Open())
                            {
                                originalFileMemoryStream.CopyTo(entryStream);
                            }
                        }
                    }
                }
                fileBytes = memoryStream.ToArray();
            }

            // download the constructed zip
            Response.Headers.Add("Content-Disposition", "attachment; filename=download.zip");
            return(File(fileBytes, "application/zip"));
        }
        /** Returns a binary reader for the data in the zip entry */
        private static BinaryReader GetBinaryReader(ZipEntry entry)
        {
#if NETFX_CORE
            return(new BinaryReader(entry.Open()));
#else
            var stream = new System.IO.MemoryStream();

            entry.Extract(stream);
            stream.Position = 0;
            return(new System.IO.BinaryReader(stream));
#endif
        }
Exemple #8
0
        private static string[] ReadConditions(System.IO.Compression.ZipArchiveEntry conditionsEntry)
        {
            string[] conditions;
            using (var condition_stream = conditionsEntry.Open())
            {
                using (var streamReader = new System.IO.StreamReader(condition_stream))
                {
                    conditions = streamReader.ReadToEnd().Split('\n');
                }
            }

            return(conditions);
        }
        /** Deserializes graph editor settings.
         * For future compatibility this method does not assume that the \a graphEditors array matches the #graphs array in order and/or count.
         * It searches for a matching graph (matching if graphEditor.target == graph) for every graph editor.
         * Multiple graph editors should not refer to the same graph.\n
         * \note Stored in files named "graph#_editor.json" where # is the graph number.
         *
         * \note This method is only used for compatibility, newer versions store everything in the graph.serializedEditorSettings field which is already serialized.
         */
        public void DeserializeEditorSettingsCompatibility()
        {
            for (int i = 0; i < graphs.Length; i++)
            {
                var      zipIndex = graphIndexInZip[graphs[i]];
                ZipEntry entry    = GetEntry("graph" + zipIndex + "_editor" + jsonExt);
                if (entry == null)
                {
                    continue;
                }

                (graphs[i] as IGraphInternals).SerializedEditorSettings = GetString(entry);
            }
        }
        /** Returns the data in the zip entry as a string */
        private static string GetString(ZipEntry entry)
        {
#if NETFX_CORE
            var reader = new StreamReader(entry.Open());
#else
            var buffer = new MemoryStream();

            entry.Extract(buffer);
            buffer.Position = 0;
            var reader = new StreamReader(buffer);
#endif
            string s = reader.ReadToEnd();
            reader.Dispose();
            return(s);
        }
Exemple #11
0
        public byte[] FetchZipOfCertificatesForUsers(int intRptID, string[] arrNames)
        {
            byte[] compressedBytes = null;

            Models.Certificate inst_report = FetchCertificatetByID(intRptID);

            if (inst_report == null)
            {
                return(compressedBytes);
            }

            inst_report.Path = Path.Combine(_ContentRootPath, inst_report.Path);

            //====================================

            using (LocalReport rpt = new LocalReport()
            {
                ReportPath = inst_report.Path,
                DisplayName = inst_report.Title
            })
                using (MemoryStream zipStream = new MemoryStream())
                {
                    using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(zipStream, System.IO.Compression.ZipArchiveMode.Create, true))
                    {
                        foreach (string strName in arrNames)
                        {
                            rpt.SetParameters(new ReportParameter()
                            {
                                Name = "Name", Values = { strName }
                            });

                            string strFileName = (strName + " " + rpt.DisplayName).Replace(" ", ".").Replace("/", ".") + ".pdf";

                            System.IO.Compression.ZipArchiveEntry entry = zip.CreateEntry(strFileName.ToLower());

                            using (Stream entryStream = entry.Open())
                                using (MemoryStream rptStream = new MemoryStream(rpt.Render("pdf")))
                                {
                                    rptStream.CopyTo(entryStream);
                                }
                        }
                    }

                    compressedBytes = zipStream.ToArray();
                }

            return(compressedBytes);
        }
Exemple #12
0
        CsvHelper.CsvReader OpenCsvFile(io.Compression.ZipArchiveEntry entry)
        {
            using (var outStream = new io.StreamReader(entry.Open()))
            {
                var content = outStream.ReadToEnd();

                byte[] byteArray = Encoding.ASCII.GetBytes(content);

                io.MemoryStream mstream = new io.MemoryStream(byteArray);

                var stream = new io.StreamReader(mstream);

                var csv = new CsvHelper.CsvReader(stream);

                return(csv);
            }
        }
Exemple #13
0
        public static JavaClassEx ReadClassEx(System.IO.Compression.ZipArchiveEntry entry,
                                              bool withCode = true)
        {
            if (entry.Length > 4 &&
                (!string.IsNullOrEmpty(Path.GetFileName(entry.FullName))))
            {
                using (var stream = entry.Open())
                {
                    var(b0, b1, b2, b3) = (stream.ReadByte(), stream.ReadByte(),
                                           stream.ReadByte(), stream.ReadByte());
                    if (b0 == 0xCA && b1 == 0xFE && b2 == 0xBA && b3 == 0xBE)
                    {
                        using (var stream2 = new MemoryStream())
                        {
                            stream2.WriteByte((byte)b0);
                            stream2.WriteByte((byte)b1);
                            stream2.WriteByte((byte)b2);
                            stream2.WriteByte((byte)b3);
                            stream.CopyTo(stream2);
                            stream2.Position = 0;

                            var whereText = $"entry '{entry.FullName}' in archive";
                            var rdr       = new JavaReader(stream2, whereText, withCode);

                            if (rdr.Class != null)
                            {
                                rdr.Class.PackageNameLength =
                                    (short)Path.GetDirectoryName(entry.FullName).Length;

                                return(new JavaClassEx
                                {
                                    JavaClass = rdr.Class,
                                    Constants = rdr.constants,
                                    RawBytes = stream2.ToArray()
                                });
                            }
                        }
                    }
                }
            }
            return(null);
        }
        static void AddAttachment(int WiID, System.IO.Compression.ZipArchiveEntry FilePath)
        {
            AttachmentReference att;

            using (var attStream = FilePath.Open())
            {
                att = WitClient.CreateAttachmentAsync(attStream, FilePath.Name).Result; // upload the file
            }
            List <object> references = new List <object>
            {
                new
                {
                    rel        = RelConstants.AttachmentRefStr,
                    url        = att.Url,
                    attributes = new { comment = "" }
                }
            };

            AddWorkItemRelations(WiID, references);
        }
Exemple #15
0
        private bool CheckZipEntryContent(System.IO.Compression.ZipArchiveEntry entry, string fileName)
        {
            using (var entryStream = entry.Open())
                using (var fileStream = File.Open(fileName, FileMode.Open))
                {
                    int entryStreamByte;
                    int fileStreamByte;
                    do
                    {
                        entryStreamByte = entryStream.ReadByte();
                        fileStreamByte  = fileStream.ReadByte();

                        if (entryStreamByte != fileStreamByte)
                        {
                            return(false);
                        }
                    } while (entryStreamByte != -1 && fileStreamByte != -1);
                }

            return(true);
        }
Exemple #16
0
        private ArraySegment <Byte> _ReadAsset(string filePath)
        {
            System.IO.Compression.ZipArchiveEntry entry = _FindEntry(filePath);

            using (var s = entry.Open())
            {
                using (var m = new System.IO.MemoryStream())
                {
                    s.CopyTo(m);

                    if (m.TryGetBuffer(out ArraySegment <Byte> data))
                    {
                        return(data);
                    }
                    else
                    {
                        return(new ArraySegment <byte>(m.ToArray()));
                    }
                }
            }
        }
        /// <summary>
        /// Checks to see if the downloaded zipball contains a psd1 file in the root folder. This is required for the powershell modules.
        /// </summary>
        /// <param name="zaitem">The ZipArchive item of the zipball.</param>
        /// <returns>True if the zipball contains a psd1 file. Default is false.</returns>
        private bool IsValidPSModule(System.IO.Compression.ZipArchive zaitem)
        {
            bool rtn = false;
            int  idx = 0;

            if (zaitem != null)
            {
                string rootfolder = zaitem.Entries[0].FullName;
                do
                {
                    System.IO.Compression.ZipArchiveEntry zaentry = zaitem.Entries[idx];
                    string filename = zaentry.FullName.Replace(rootfolder, "");
                    if (!filename.Contains("/") && filename.Contains(".psd1"))
                    {
                        rtn = true;
                    }
                    idx++;
                } while (!rtn && idx < zaitem.Entries.Count());
            }
            return(rtn);
        }
        public IActionResult Download()
        {
            IList <Anexo> sourceFiles = AnexoRepository.anexos;

            // ...

            // the output bytes of the zip
            byte[] fileBytes = null;

            // create a working memory stream
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                // create a zip
                using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
                {
                    // interate through the source files
                    foreach (var f in sourceFiles)
                    {
                        // add the item name to the zip
                        System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(f.Name);
                        // add the item bytes to the zip entry by opening the original file and copying the bytes
                        using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(f.file))
                        {
                            using (System.IO.Stream entryStream = zipItem.Open())
                            {
                                originalFileMemoryStream.CopyTo(entryStream);
                            }
                        }
                    }
                }
                fileBytes = memoryStream.ToArray();
            }

            // download the constructed zip
            Response.Headers.Add("Content-Disposition", "attachment; filename=download.zip");

            // .("Content-Disposition", "attachment; filename=download.zip");
            return(File(fileBytes, "application/zip"));
        }
Exemple #19
0
            public static string CreateJCOBridgeZip(string rootFolder)
            {
                var frameworkPath = Path.Combine(rootFolder, BinDirectory, Framework.RuntimeFolder);
                var localArchive  = Path.Combine(frameworkPath, JCOBridgeEmbeddedFile);

                if (File.Exists(localArchive))
                {
                    File.Delete(localArchive);
                }
                using (var archive = System.IO.Compression.ZipFile.Open(localArchive, System.IO.Compression.ZipArchiveMode.Create))
                {
                    foreach (var item in JCOBridgeFiles)
                    {
                        System.IO.Compression.ZipArchiveEntry entry = archive.CreateEntry(item, System.IO.Compression.CompressionLevel.Optimal);
                        using (StreamWriter writer = new StreamWriter(entry.Open()))
                        {
                            byte[] buffer = File.ReadAllBytes(Path.Combine(frameworkPath, item));
                            writer.BaseStream.Write(buffer, 0, buffer.Length);
                        }
                    }
                }
                return(localArchive);
            }
Exemple #20
0
        public static JavaClass ReadClass(System.IO.Compression.ZipArchiveEntry entry,
                                          bool withCode = true)
        {
            JavaClass jclass = null;

            if ((!string.IsNullOrEmpty(Path.GetFileName(entry.FullName))) &&
                entry.Length > 4)
            {
                using (var stream = entry.Open())
                {
                    var(b0, b1, b2, b3) = (stream.ReadByte(), stream.ReadByte(),
                                           stream.ReadByte(), stream.ReadByte());
                    if (b0 == 0xCA && b1 == 0xFE && b2 == 0xBA && b3 == 0xBE)
                    {
                        using (var stream2 = new MemoryStream())
                        {
                            stream2.WriteByte((byte)b0);
                            stream2.WriteByte((byte)b1);
                            stream2.WriteByte((byte)b2);
                            stream2.WriteByte((byte)b3);
                            stream.CopyTo(stream2);
                            stream2.Position = 0;

                            var whereText = $"entry '{entry.FullName}' in archive";
                            jclass = (new JavaReader(stream2, whereText, withCode)).Class;

                            if (jclass != null)
                            {
                                jclass.PackageNameLength =
                                    (short)Path.GetDirectoryName(entry.FullName).Length;
                            }
                        }
                    }
                }
            }
            return(jclass);
        }
        /// <summary> 解压数据 </summary>
        public static byte[] Decompress(Stream source)
        {
#if false//SCORPIO_UWP && !UNITY_EDITOR
            using (MemoryStream stream = new MemoryStream()) {
                System.IO.Compression.ZipArchive      zipStream = new System.IO.Compression.ZipArchive(source, System.IO.Compression.ZipArchiveMode.Read);
                System.IO.Compression.ZipArchiveEntry zipEntry  = zipStream.Entries[0];
                Stream entryStream = zipEntry.Open();
                int    count       = 0;
                byte[] data        = new byte[4096];
                while ((count = entryStream.Read(data, 0, data.Length)) != 0)
                {
                    stream.Write(data, 0, count);
                }
                zipStream.Dispose();
                byte[] ret = stream.ToArray();
                stream.Dispose();
                return(ret);
            }
#else
            using (MemoryStream stream = new MemoryStream()) {
                ICSharpCode.SharpZipLib.Zip.ZipInputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(source);
                zipStream.GetNextEntry();
                int    count = 0;
                byte[] data  = new byte[4096];
                while ((count = zipStream.Read(data, 0, data.Length)) != 0)
                {
                    stream.Write(data, 0, count);
                }
                zipStream.Flush();
                byte[] ret = stream.ToArray();
                zipStream.Dispose();
                stream.Dispose();
                return(ret);
            }
#endif
        }
 private GraphMeta DeserializeMeta(ZipEntry entry)
 {
     return(TinyJsonDeserializer.Deserialize(GetString(entry), typeof(GraphMeta)) as GraphMeta);
 }
Exemple #23
0
 public static void ExtractToFile(this System.IO.Compression.ZipArchiveEntry source, string destinationFileName, bool overwrite)
 {
 }
Exemple #24
0
 public SystemIOCompressionArchiveEntry(System.IO.Compression.ZipArchiveEntry entry)
 {
     this.BaseEntry = entry;
 }
        private void ImportCoordsBtn_Click(object sender, RoutedEventArgs e)
        {
            // File Input Dialog
            //Microsoft.Win32.OpenFileDialog fileDialog = new Microsoft.Win32.OpenFileDialog();
            //fileDialog.Title = "Select file to Import";
            //fileDialog.Filter = "Supported files (*.xml, *.json)|*.xml; *.json|All files (*.*)|*.*";
            //fileDialog.ShowDialog();

            Microsoft.Win32.OpenFileDialog fileDialog = new Microsoft.Win32.OpenFileDialog
            {
                Title       = "Select file to Import",
                Filter      = "Supported files (*.cf, *.json)|*.cf; *.json|All files (*.*)|*.*",
                Multiselect = false
            };



            if (fileDialog.ShowDialog() == true)
            {
                // Handle CF File (from Combat Flite)
                if (fileDialog.SafeFileName.EndsWith("cf"))
                {
                    System.IO.Compression.ZipArchive cfFile = System.IO.Compression.ZipFile.Open(fileDialog.FileName, System.IO.Compression.ZipArchiveMode.Read);
                    foreach (System.IO.Compression.ZipArchiveEntry entry in cfFile.Entries)
                    {
                        if (entry.Name.ToUpper().EndsWith(".XML"))
                        {
                            System.IO.Compression.ZipArchiveEntry zipEntry = cfFile.GetEntry(entry.Name);

                            using (System.IO.StreamReader sr = new System.IO.StreamReader(zipEntry.Open()))
                            {
                                // Handle XML file
                                //var xml = XDocument.Load(fileDialog.FileName);
                                var xml = XDocument.Parse(sr.ReadToEnd());

                                IEnumerable <XElement> waypoints = xml.Root.Descendants("Waypoints").Elements();
                                foreach (var wp in waypoints)
                                {
                                    Console.WriteLine(wp);

                                    string xmlName = wp.Element("Name").Value;
                                    string xmlLat  = wp.Element("Lat").Value;
                                    string xmlLon  = wp.Element("Lon").Value;
                                    string xmlAlt  = wp.Element("Altitude").Value;

                                    //Console.WriteLine(xmlLat);
                                    //Console.WriteLine(xmlLon);
                                    //Console.WriteLine(xmlAlt);

                                    DDMCoord lat = new DDMCoord();
                                    DDMCoord lon = new DDMCoord();

                                    lat.fromDD(double.Parse(xmlLat, System.Globalization.CultureInfo.InvariantCulture));
                                    lon.fromDD(double.Parse(xmlLon, System.Globalization.CultureInfo.InvariantCulture));

                                    // Crate new Coordinate
                                    Coordinate tempCoord = new Coordinate();
                                    tempCoord.id         = newCoordId.Text;
                                    tempCoord.name       = xmlName;
                                    tempCoord.latitude   = string.Format("2{0:D2}{1:D2}{2:D3}", lat.deg, (int)lat.dec, (int)((lat.dec - (int)lat.dec) * 1000));
                                    tempCoord.longditude = string.Format("6{0:D3}{1:D2}{2:D3}", lon.deg, (int)lon.dec, (int)((lon.dec - (int)lon.dec) * 1000));
                                    tempCoord.elevation  = string.Format("{0:F0}", xmlAlt);

                                    // Add coordinate to the DataGrid
                                    DataGridCoords.Items.Add(tempCoord);

                                    // Autoincrement the ID
                                    newCoordId.Text = Convert.ToString(Convert.ToInt16(newCoordId.Text) + 1);
                                }
                            }
                        }
                    }
                }
                else if (fileDialog.SafeFileName.EndsWith("json"))
                // Handle JSON file (From mdc.hoelweb.com)
                {
                    using (JsonDocument missionJson = JsonDocument.Parse(File.ReadAllText(fileDialog.FileName), new JsonDocumentOptions {
                        AllowTrailingCommas = true
                    }))
                    {
                        var waypoints = missionJson.RootElement.GetProperty("waypoints").EnumerateArray();

                        foreach (JsonElement wp in waypoints)
                        {
                            //Console.WriteLine(wp.GetProperty("wp"));

                            string wpName = wp.GetProperty("wp").GetString();
                            string wpLat  = wp.GetProperty("lat").GetString();
                            string wpLon  = wp.GetProperty("lon").GetString();
                            string wpAlt  = wp.GetProperty("alt").GetString();

                            DDMCoord lat = new DDMCoord();
                            DDMCoord lon = new DDMCoord();

                            lat.fromDD(double.Parse(wpLat, System.Globalization.CultureInfo.InvariantCulture));
                            lon.fromDD(double.Parse(wpLon, System.Globalization.CultureInfo.InvariantCulture));

                            // Create Coordinate
                            Coordinate tempCoord = new Coordinate();
                            tempCoord.id         = newCoordId.Text;
                            tempCoord.name       = wpName;
                            tempCoord.latitude   = string.Format("2{0:D2}{1:D2}{2:D3}", lat.deg, (int)lat.dec, (int)((lat.dec - (int)lat.dec) * 1000));
                            tempCoord.longditude = string.Format("6{0:D3}{1:D2}{2:D3}", lon.deg, (int)lon.dec, (int)((lon.dec - (int)lon.dec) * 1000));
                            tempCoord.elevation  = string.Format("{0:F0}", wpAlt);

                            //Console.WriteLine(tempCoord.latitude);
                            //Console.WriteLine(tempCoord.longditude);
                            //Console.WriteLine(tempCoord.elevation);

                            // Add coordinate to the DataGrid
                            DataGridCoords.Items.Add(tempCoord);

                            // Autoincrement the ID
                            newCoordId.Text = Convert.ToString(Convert.ToInt16(newCoordId.Text) + 1);
                        }
                    }
                }
            }
        }
Exemple #26
0
 public capex.util.ZipReaderForDotNet.MyZipReaderEntry setEntry(System.IO.Compression.ZipArchiveEntry v)
 {
     entry = v;
     return(this);
 }
Exemple #27
0
        public static byte[] Compress(IList <SourceFile> sourceFiles)
        {
            // get the source files
            //List<SourceFile> sourceFiles = new List<SourceFile>();
            // ...

            // the output bytes of the zip
            //byte[] fileBytes = null;

            string FileName;

            // create a working memory stream
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                // create a zip
                using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
                {
                    // interate through the source files
                    foreach (SourceFile f in sourceFiles)
                    {
                        //VALIDAZIONE
                        if (string.IsNullOrWhiteSpace(f.Name))
                        {
                            throw new ArgumentNullException(nameof(f.Name));
                        }
                        if (string.IsNullOrWhiteSpace(f.Extension))
                        {
                            throw new ArgumentNullException(nameof(f.Extension));
                        }
                        if (f.FileBytes == null)
                        {
                            throw new ArgumentNullException(nameof(f.FileBytes));
                        }

                        //NORMALIZZO NOME ED ESTENSIONE
                        FileName = f.Name.Trim();
                        if (FileName.Substring(FileName.Length - 1) == ".")
                        {
                            FileName = FileName.Substring(0, FileName.Length - 2);
                        }

                        if (f.Extension.Trim().Substring(0, 1) == ".")
                        {
                            FileName = FileName + f.Extension.Trim();
                        }
                        else
                        {
                            FileName = $"{FileName}.{f.Extension}";
                        }

                        //CONTROLLO CHE IL NOME DEL FILE O L'ESTENSIONE NO  CONTENGANO CARATTERI NON VALIDI
                        Regex containsABadCharacter = new Regex("[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "]");
                        if (containsABadCharacter.IsMatch(FileName))
                        {
                            throw new Exception("File Name or Extension constains invalid characters");
                        }

                        // add the item name to the zip
                        System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(FileName);
                        // add the item bytes to the zip entry by opening the original file and copying the bytes
                        using (MemoryStream originalFileMemoryStream = new MemoryStream(f.FileBytes))
                        {
                            using (Stream entryStream = zipItem.Open())
                            {
                                originalFileMemoryStream.CopyTo(entryStream);
                            }
                        }
                    }
                }
                //fileBytes = memoryStream.ToArray();
                return(memoryStream.ToArray());
            }

            // download the constructed zip
            //Response.AddHeader("Content-Disposition", "attachment; filename=download.zip");
            //return File(fileBytes, "application/zip");
        }
        public override void SaveDirectory(Plan Plan, PlanExecutionStatus Status, string Path, List <string> NewDirectories, List <string> NewFiles)
        {
            /*
             * if (Path.ToLower() == Plan.Source.ToLower())
             * {
             *  string[] subDirs = Worker.listDirs(Plan, Path);
             *  NewDirectories.AddRange(subDirs);
             *  return;
             * }
             * if (!Path.ToLower().Contains("voidrats"))
             *  return;
             */

            string   src          = Path;
            string   dst          = System.IO.Path.Combine(Plan.Destination, Worker.stripSource(Plan.Source, Path));
            DateTime lastBackup   = DateTime.MinValue;
            DateTime lastModified = DateTime.MinValue;
            bool     isProject    = Worker.IsProjectDirectory(Plan, Path);


            #region Determine latest file to be backed up
            string[] filesToSave;
            if (isProject)
            {
                filesToSave = Worker.listFilesRecursive(Plan, src);
            }
            else
            {
                filesToSave = Worker.listFiles(Plan, src);
            }
            for (int i = 0; i < filesToSave.Length; i++)
            {
                System.IO.FileInfo info = new System.IO.FileInfo(filesToSave[i]);
                if (lastModified < info.CreationTime)
                {
                    lastModified = info.CreationTime;
                }
                if (lastModified < info.LastWriteTime)
                {
                    lastModified = info.LastWriteTime;
                }
            }
            #endregion

            #region Determine latest backup
            if (System.IO.Directory.Exists(dst))
            {
                string[] tmp = System.IO.Directory.GetFiles(dst, "Backup *.zip");
                for (int i = 0; i < tmp.Length; i++)
                {
                    DateTime fileSaved = DateTime.MinValue;

                    if (DateTime.TryParseExact(System.IO.Path.GetFileNameWithoutExtension(tmp[i]).Substring(7),
                                               "yyyy_MM_dd HH_mm_ss",
                                               System.Globalization.CultureInfo.InvariantCulture,
                                               System.Globalization.DateTimeStyles.None,
                                               out fileSaved))
                    {
                        if (lastBackup < fileSaved)
                        {
                            lastBackup = fileSaved;
                        }
                    }
                }
            }
            #endregion

            #region Compare list of files in folder vs. list of files in latest .ZIP file
            if (lastBackup != DateTime.MinValue)
            {
                List <string> filesRemaining = new List <string>(filesToSave);
                try
                {
                    System.IO.Compression.ZipArchive zip = System.IO.Compression.ZipFile.Open(
                        System.IO.Path.Combine(dst, "Backup " + lastBackup.ToString("yyyy_MM_dd HH_mm_ss") + ".zip"),
                        System.IO.Compression.ZipArchiveMode.Read);

                    foreach (System.IO.Compression.ZipArchiveEntry entry in zip.Entries)
                    {
                        bool wasFound = false;
                        for (int i = 0; i < filesRemaining.Count; i++)
                        {
                            if (entry.FullName.ToUpper() == Worker.stripSource(Path, filesRemaining[i].ToUpper()))
                            {
                                wasFound = true;
                                filesRemaining.RemoveAt(i);
                                break;
                            }
                        }

                        if (!wasFound)
                        {
                            lastBackup = DateTime.MinValue;
                            break;
                        }
                    }

                    zip.Dispose();
                }
                catch (Exception e)
                {
                    if (e.Message == "Central Directory corrupt.")
                    {
                        System.IO.File.Delete(System.IO.Path.Combine(dst, "Backup " + lastBackup.ToString("yyyy_MM_dd HH_mm_ss") + ".zip"));
                    }
                    else
                    {
                        throw e;
                    }
                }

                while (filesRemaining.Count > 0)
                {
                    if (System.IO.File.Exists(
                            System.IO.Path.Combine(dst, "Backup " + lastBackup.ToString("yyyy_MM_dd HH_mm_ss") + System.IO.Path.GetFileName(filesRemaining[0]))
                            ))
                    {
                        filesRemaining.RemoveAt(0);
                    }
                    else
                    {
                        break;
                    }
                }

                if (filesRemaining.Count > 0)
                {
                    lastBackup = DateTime.MinValue;
                }
            }
            #endregion

            #region Do we need to create the zip file?
            if (lastModified > lastBackup)
            {
                // Create zip file
                string path   = System.IO.Path.GetTempFileName();
                string pathTo = System.IO.Path.Combine(dst, "Backup " + Plan.LastAttmpted.ToString("yyyy_MM_dd HH_mm_ss") + ".zip");
                System.IO.Compression.ZipArchive zip = System.IO.Compression.ZipFile.Open(
                    path,
                    System.IO.Compression.ZipArchiveMode.Update);
                // Add each file
                for (int i = 0; i < filesToSave.Length; i++)
                {
                    System.IO.FileInfo info = new System.IO.FileInfo(filesToSave[i]);
                    #region If this is a small file (under 20mb), add to the zip file
                    if (info.Length < 20 * 1024 * 1024)
                    {
                        #region Every 250 files, close and reopen the ZIP file (this keeps memory from just growing stupidly)
                        if (i % 250 == 0)
                        {
                            zip.Dispose();
                            zip = System.IO.Compression.ZipFile.Open(
                                path,
                                System.IO.Compression.ZipArchiveMode.Update);
                        }
                        #endregion
                        #region Add file to .ZIP file
                        try
                        {
                            System.IO.Compression.ZipArchiveEntry entry =
                                System.IO.Compression.ZipFileExtensions.CreateEntryFromFile(
                                    zip,
                                    filesToSave[i],
                                    Worker.stripSource(Path, filesToSave[i]));
                        }
                        #endregion
                        #region Catch I/O exceptions
                        catch (System.IO.IOException)
                        {
                            zip.Dispose();
                            System.IO.File.Delete(path);
                            if (!isProject)
                            {
                                string[] subDirs = Worker.listDirs(Plan, src);
                                NewDirectories.AddRange(subDirs);
                            }
                            return;
                        }
                        #endregion
                        #region Catch access exceptions
                        catch (System.UnauthorizedAccessException)
                        {
                            zip.Dispose();
                            System.IO.File.Delete(path);
                            if (!isProject)
                            {
                                string[] subDirs = Worker.listDirs(Plan, src);
                                NewDirectories.AddRange(subDirs);
                            }
                            return;
                        }
                        #endregion
                        #region Catch out of memory exceptions (close and reopen .ZIP file)
                        catch (OutOfMemoryException)
                        {
                            zip.Dispose();
                            zip = System.IO.Compression.ZipFile.Open(
                                path,
                                System.IO.Compression.ZipArchiveMode.Update);

                            System.IO.Compression.ZipArchiveEntry entry =
                                System.IO.Compression.ZipFileExtensions.CreateEntryFromFile(
                                    zip,
                                    filesToSave[i],
                                    Worker.stripSource(Path, filesToSave[i]),
                                    System.IO.Compression.CompressionLevel.NoCompression);
                        }
                        #endregion
                    }
                    #endregion
                    #region IF this is a large file, copy as is
                    else
                    {
                        if (!System.IO.Directory.Exists(
                                System.IO.Path.GetDirectoryName(pathTo)))
                        {
                            System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(pathTo));
                        }

                        if (System.IO.File.Exists(System.IO.Path.GetDirectoryName(pathTo)))
                        {
                            System.IO.File.Delete(System.IO.Path.GetDirectoryName(pathTo));
                        }

                        System.IO.File.Copy(
                            filesToSave[i],
                            System.IO.Path.Combine(System.IO.Path.GetDirectoryName(pathTo), "Backup " + Plan.LastAttmpted.ToString("yyyy_MM_dd HH_mm_ss") + info.Name + ".tmp")
                            );

                        if (System.IO.File.Exists(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(pathTo), "Backup " + Plan.LastAttmpted.ToString("yyyy_MM_dd HH_mm_ss") + info.Name)))
                        {
                            System.IO.File.Delete(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(pathTo), "Backup " + Plan.LastAttmpted.ToString("yyyy_MM_dd HH_mm_ss") + info.Name));
                        }

                        System.IO.File.Move(
                            System.IO.Path.Combine(System.IO.Path.GetDirectoryName(pathTo), "Backup " + Plan.LastAttmpted.ToString("yyyy_MM_dd HH_mm_ss") + info.Name + ".tmp"),
                            System.IO.Path.Combine(System.IO.Path.GetDirectoryName(pathTo), "Backup " + Plan.LastAttmpted.ToString("yyyy_MM_dd HH_mm_ss") + info.Name)
                            );
                    }
                    #endregion
                }
                zip.Dispose();
                if (!System.IO.Directory.Exists(
                        System.IO.Path.GetDirectoryName(pathTo)))
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(pathTo));
                }
                if (System.IO.File.Exists(pathTo + ".tmp"))
                {
                    System.IO.File.Delete(pathTo + ".tmp");
                }
                System.IO.File.Move(path, pathTo + ".tmp");
                if (System.IO.File.Exists(pathTo))
                {
                    System.IO.File.Delete(pathTo);
                }
                System.IO.File.Move(pathTo + ".tmp", pathTo);
            }
            #endregion

            #region Add all subdirectories
            if (!isProject)
            {
                string[] subDirs = Worker.listDirs(Plan, src);
                NewDirectories.AddRange(subDirs);
            }
            #endregion
        }
        public ActionResult ZipAndDownloadFiles(string fileName)
        {
            string filePath = Server.MapPath("~") + @"ExtractedTemplate\" + fileName;

            try
            {
                CreateZips.SourceDirectoriesFiles sfiles = new CreateZips.SourceDirectoriesFiles();
                if (System.IO.Directory.Exists(filePath))
                {
                    string[] files   = Directory.GetFiles(filePath);
                    string[] subDirs = Directory.GetDirectories(filePath);
                    if (files.Length > 0)
                    {
                        sfiles.Files = new List <CreateZips.FileInfo>();

                        foreach (var f in files)
                        {
                            CreateZips.FileInfo fileInfo = new CreateZips.FileInfo();

                            string[] fSplit      = f.Split('\\');
                            string   splitLength = fSplit[fSplit.Length - 1];
                            fSplit = splitLength.Split('.');

                            fileInfo.Name      = fSplit[0];
                            fileInfo.Extension = fSplit[1];
                            fileInfo.FileBytes = System.IO.File.ReadAllBytes(f);
                            sfiles.Files.Add(fileInfo);
                        }
                    }

                    if (subDirs.Length > 0)
                    {
                        sfiles.Folder = new List <CreateZips.Folder>();

                        foreach (var dir in subDirs)
                        {
                            string[] subDirFiles   = System.IO.Directory.GetFiles(dir);
                            string[] subDirsLevel2 = Directory.GetDirectories(dir);

                            if (subDirFiles.Length > 0)
                            {
                                CreateZips.Folder folder        = new CreateZips.Folder();
                                string[]          getFolderName = dir.Split('\\');
                                string            subFolderName = getFolderName[getFolderName.Length - 1];
                                folder.FolderName  = subFolderName;
                                folder.FolderItems = new List <CreateZips.FolderItem>();

                                foreach (var sdf in subDirFiles)
                                {
                                    CreateZips.FolderItem folderItem = new CreateZips.FolderItem();
                                    string[] fSplit      = sdf.Split('\\');
                                    string   splitLength = fSplit[fSplit.Length - 1];
                                    fSplit = splitLength.Split('.');

                                    folderItem.Name      = fSplit[0];
                                    folderItem.Extension = fSplit[1];
                                    folderItem.FileBytes = System.IO.File.ReadAllBytes(sdf);
                                    folder.FolderItems.Add(folderItem);
                                }
                                if (subDirsLevel2.Length > 0)
                                {
                                    folder.FolderL2 = new List <CreateZips.FolderL2>();
                                    foreach (var dirL2 in subDirsLevel2)
                                    {
                                        string[] subDirFilesL2 = System.IO.Directory.GetFiles(dirL2);
                                        if (subDirFilesL2.Length > 0)
                                        {
                                            CreateZips.FolderL2 folderFL2       = new CreateZips.FolderL2();
                                            string[]            getFolderNameL2 = dirL2.Split('\\');
                                            string subFolderNameL2 = getFolderNameL2[getFolderNameL2.Length - 1];
                                            folderFL2.FolderName  = subFolderNameL2;
                                            folderFL2.FolderItems = new List <CreateZips.FolderItem>();

                                            foreach (var sdfL2 in subDirFilesL2)
                                            {
                                                CreateZips.FolderItem folderItem = new CreateZips.FolderItem();
                                                string[] fSplit      = sdfL2.Split('\\');
                                                string   splitLength = fSplit[fSplit.Length - 1];
                                                fSplit = splitLength.Split('.');

                                                folderItem.Name      = fSplit[0];
                                                folderItem.Extension = fSplit[1];
                                                folderItem.FileBytes = System.IO.File.ReadAllBytes(sdfL2);
                                                folderFL2.FolderItems.Add(folderItem);
                                            }
                                            folder.FolderL2.Add(folderFL2);
                                        }
                                    }
                                }
                                sfiles.Folder.Add(folder);
                            }
                        }
                    }
                }
                // ...

                // the output bytes of the zip
                byte[] fileBytes = null;

                //create a working memory stream
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                {
                    // create a zip
                    using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
                    {
                        // interate through the source files
                        if (sfiles.Folder != null && sfiles.Folder.Count > 0)
                        {
                            //each folder in source file [depth 1]
                            foreach (var folder in sfiles.Folder)
                            {
                                // add the item name to the zip
                                // each file in the folder
                                foreach (var file in folder.FolderItems)
                                {
                                    // folder items - file name, extension, and file bytes or content in bytes
                                    // zip.CreateEntry can create folder or the file. If you just provide a name, it will create a folder (if it doesn't not exist). If you provide with extension, it will create file
                                    System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(folder.FolderName + "/" + file.Name + "." + file.Extension); // Creating folder and create file inside that folder

                                    using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(file.FileBytes))                         // adding file bytes to memory stream object
                                    {
                                        using (System.IO.Stream entryStream = zipItem.Open())                                                                    // opening the folder/file
                                        {
                                            originalFileMemoryStream.CopyTo(entryStream);                                                                        // copy memory stream dat bytes to file created
                                        }
                                    }
                                    // for second level of folder like /Template/Teams/BoardColums.json
                                    //each folder in source file [depth 2]
                                    if (folder.FolderL2 != null && folder.FolderL2.Count > 0)
                                    {
                                        foreach (var folder2 in folder.FolderL2)
                                        {
                                            foreach (var file2 in folder2.FolderItems)
                                            {
                                                System.IO.Compression.ZipArchiveEntry zipItem2 = zip.CreateEntry(folder.FolderName + "/" + folder2.FolderName + "/" + file2.Name + "." + file2.Extension);
                                                using (System.IO.MemoryStream originalFileMemoryStreamL2 = new System.IO.MemoryStream(file2.FileBytes))
                                                {
                                                    using (System.IO.Stream entryStreamL2 = zipItem2.Open())
                                                    {
                                                        originalFileMemoryStreamL2.CopyTo(entryStreamL2);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (sfiles.Files != null && sfiles.Files.Count > 0)
                        {
                            foreach (var outerFile in sfiles.Files)
                            {
                                // add the item name to the zip
                                System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(outerFile.Name + "." + outerFile.Extension);
                                // add the item bytes to the zip entry by opening the original file and copying the bytes
                                using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(outerFile.FileBytes))
                                {
                                    using (System.IO.Stream entryStream = zipItem.Open())
                                    {
                                        originalFileMemoryStream.CopyTo(entryStream);
                                    }
                                }
                            }
                        }
                    }
                    fileBytes = memoryStream.ToArray();
                }
                // download the constructed zip
                Directory.Delete(filePath, true);
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip");
                return(File(fileBytes, "application/zip"));
            }
            catch (Exception ex)
            {
                ExtractorService.logger.Info(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + "\t" + ex.Message + "\n" + ex.StackTrace + "\n");
            }
            finally
            {
                if (Directory.Exists(filePath))
                {
                    Directory.Delete(filePath, true);
                }
            }
            ViewBag.Error = "File not found";
            return(RedirectToAction("Index", "Extractor"));
        }
        public ActionResult DownloadAttachments(string data)
        {
            Download model = JsonConvert.DeserializeObject <Download>(data);


            CreateZip.DirectoriesFiles sfiles = new CreateZip.DirectoriesFiles
            {
                Files  = new List <CreateZip.FileInfo>(),
                Folder = new List <CreateZip.Folder>()
            };
            try
            {
                if (Convert.ToString(Session["PAT"]) != null)
                {
                    string     token      = Convert.ToString(Session["PAT"]);
                    CLWorkItem cLWorkItem = new CLWorkItem(token);
                    // the output bytes of the zip
                    byte[] fileBytes = null;
                    if (model.ExportType == "File")
                    {
                        foreach (var wi in model.DocumentIds)
                        {
                            CreateZip.FileInfo fileInfo = new CreateZip.FileInfo();
                            fileInfo.FileBytes = cLWorkItem.DownloadAttachment(model.AccountName, model.ProjectName, wi.DocId, wi.DocName);
                            String docName           = wi.DocName;
                            int    index             = docName.LastIndexOf(".");
                            String documentName      = docName.Substring(0, index);
                            String documentExtension = docName.Substring(index + 1);
                            fileInfo.Name      = wi.WorkItemId + "__" + documentName;
                            fileInfo.Extension = documentExtension;
                            sfiles.Files.Add(fileInfo);
                        }

                        //create a working memory stream
                        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                        {
                            // create a zip
                            using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
                            {
                                if (sfiles.Files != null && sfiles.Files.Count > 0)
                                {
                                    foreach (var outerFile in sfiles.Files)
                                    {
                                        // add the item name to the zip
                                        System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(outerFile.Name + "." + outerFile.Extension);
                                        // add the item bytes to the zip entry by opening the original file and copying the bytes
                                        using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(outerFile.FileBytes))
                                        {
                                            using (System.IO.Stream entryStream = zipItem.Open())
                                            {
                                                originalFileMemoryStream.CopyTo(entryStream);
                                            }
                                        }
                                    }
                                }
                            }
                            fileBytes = memoryStream.ToArray();
                        }
                    }
                    else
                    {
                        CreateZip.Folder folder = new CreateZip.Folder();
                        foreach (var wi in model.DocumentIds)
                        {
                            CreateZip.Folder folderq = new CreateZip.Folder();
                            folderq.FolderItems = new List <CreateZip.FolderItem>();

                            CreateZip.FolderItem folderItem = new CreateZip.FolderItem();
                            folderq.FolderName = wi.WorkItemId;
                            String fDocName            = wi.DocName;
                            int    fIndex              = fDocName.LastIndexOf(".");
                            String folderItemName      = fDocName.Substring(0, fIndex);
                            String folderItemExtension = fDocName.Substring(fIndex + 1);
                            folderItem.Name      = folderItemName;
                            folderItem.Extension = folderItemExtension;
                            folderItem.FileBytes = cLWorkItem.DownloadAttachment(model.AccountName, model.ProjectName, wi.DocId, wi.DocName);
                            folderq.FolderItems.Add(folderItem);
                            sfiles.Folder.Add(folderq);
                        }

                        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                        {
                            // create a zip
                            using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
                            {
                                if (sfiles.Folder != null && sfiles.Folder.Count > 0)
                                {
                                    foreach (var fldr in sfiles.Folder)
                                    {
                                        // add the item name to the zip
                                        // each file in the folder
                                        foreach (var file in fldr.FolderItems)
                                        {
                                            // add the item name to the zip
                                            System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(fldr.FolderName + "/" + file.Name + "." + file.Extension);
                                            // add the item bytes to the zip entry by opening the original file and copying the bytes
                                            using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(file.FileBytes))
                                            {
                                                using (System.IO.Stream entryStream = zipItem.Open())
                                                {
                                                    originalFileMemoryStream.CopyTo(entryStream);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            fileBytes = memoryStream.ToArray();
                        }
                    }
                    // download the constructed zip
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + "WIAttachments_" + model.ProjectName + ".zip");
                    return(File(fileBytes, "application/zip"));
                }
                else
                {
                    return(RedirectToAction("../Account/Verify"));
                }
            }
            catch (Exception ex)
            {
                logger.Append(ex.Message);
                logger.Append(ex.StackTrace);

                return(RedirectToAction("../Account/Verify"));
            }
        }