Пример #1
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);
        }
Пример #2
0
        /// <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
        }
Пример #3
0
        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"));
        }
Пример #4
0
        /** 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
        }
Пример #5
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);
        }
Пример #6
0
        /** 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);
        }
Пример #7
0
 public override cape.Reader getContentReader()
 {
     System.IO.Stream stream = null;
     try {
         stream = entry.Open();
     }
     catch (System.Exception e) {
         stream = null;
     }
     if (!(stream != null))
     {
         return(null);
     }
     return((cape.Reader)cape.DotNetStreamReader.forStream(stream));
 }
Пример #8
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);
        }
Пример #9
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);
            }
        }
Пример #10
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);
        }
Пример #12
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()));
                    }
                }
            }
        }
Пример #13
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);
        }
Пример #14
0
        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"));
        }
Пример #15
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);
            }
Пример #16
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);
        }
Пример #17
0
        /// <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
        }
Пример #18
0
        public bool WriteFile(string filename)
        {
            StreamWriter sw = null;


            FolderPath = Path.GetDirectoryName(filename);
            string fn = Path.GetFileNameWithoutExtension(filename);

            char[] chars = Path.GetInvalidFileNameChars();
            foreach (char c in chars)
            {
                fn = fn.Replace(c, '_');
            }
            FileName = Path.Combine(FolderPath, fn + Path.GetExtension(filename));
            if (filename.EndsWith("xml"))
            {
                WriteXMLFile(FileName);
                return(true);
            }
#if (!NOIFCJSON)
            else if (FileName.EndsWith("json"))
            {
                ToJSON(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");
            foreach (BaseClassIfc e in this)
            {
                if (e != null)
                {
                    try
                    {
                        string str = e.ToString();
                        if (!string.IsNullOrEmpty(str))
                        {
                            sw.WriteLine(str);
                        }
                    }
                    catch (Exception) { }
                }
            }
            sw.Write(getFooterString());
            sw.Close();
            Thread.CurrentThread.CurrentUICulture = current;
#if (!NOIFCZIP)
            if (zip)
            {
                za.Dispose();
            }
#endif
            return(true);
        }
        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"));
            }
        }
Пример #21
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");
        }
Пример #22
0
        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);
                        }
                    }
                }
            }
        }