Beispiel #1
0
    public void create_zip(string path, string filename, string type)
    {
        string fileNew;

        // Try
        fileNew = (filename + ".zip");
        //string f;
        string[] fname = Directory.GetFiles(path, type);
        ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipoutputstream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create((path + fileNew)));
        zipoutputstream.SetLevel(6);
        ICSharpCode.SharpZipLib.Checksums.Crc32 objcrc32 = new ICSharpCode.SharpZipLib.Checksums.Crc32();
        foreach (string f in fname)
        {
            FileStream stream = File.OpenRead(f);
            byte[]     buff   = new byte[stream.Length];
            ICSharpCode.SharpZipLib.Zip.ZipEntry zipentry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(f.Substring((f.LastIndexOf("\\") + 1)));
            //stream.Read(buff, 0, buff.Length);
            stream.Read(buff, 0, buff.Length);
            zipentry.DateTime = DateTime.UtcNow.AddHours(5.5);
            zipentry.Size     = stream.Length;
            stream.Close();
            objcrc32.Reset();
            objcrc32.Update(buff);
            // zipentry.Crc = objcrc32.Value;
            zipoutputstream.PutNextEntry(zipentry);
            zipoutputstream.Write(buff, 0, buff.Length);
        }
        zipoutputstream.Flush();
        zipoutputstream.Finish();
        zipoutputstream.Close();
    }
Beispiel #2
0
    public void Compress(System.IO.Stream OutputStream, System.IO.Stream InputStream)
    {
        ICSharpCode.SharpZipLib.Zip.ZipOutputStream Compressor = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(OutputStream);
        Compressor.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry("Entry"));

        byte[] buf = new byte[1024];
        int    n   = 0;

        while (true)
        {
            n = InputStream.Read(buf, 0, buf.Length);

            if (n == 0)
            {
                break;
            }
            else
            {
                Compressor.Write(buf, 0, n);
            }
        }

        Compressor.Flush();
        Compressor.Close();

        //delete(Compressor);
        //delete(buf);

        //OutputStream.Seek(0, System.IO.SeekOrigin.Begin);
    }
Beispiel #3
0
        public static string PackToBase64(byte[] data)
        {
            byte[]       buffer;
            MemoryStream ms = new MemoryStream();

            using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms))
            {
                zipOutputStream.SetLevel(9);


                ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Boliglag.Admin");
                zipOutputStream.PutNextEntry(zipEntry);

                zipOutputStream.Write(data, 0, data.Length);

                zipOutputStream.Flush();
                zipOutputStream.Finish();

                buffer      = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, Convert.ToInt32(ms.Length));
            }//using ( ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream( fileStreamOut ) ) ...

            return(ToBase64(buffer));
        }
Beispiel #4
0
        public static string PackToBase64(string text)
        {
            byte[]       buffer;
            MemoryStream ms = new MemoryStream();

            using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms))
            {
                zipOutputStream.SetLevel(9);


                ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Boliglag.Admin");
                zipOutputStream.PutNextEntry(zipEntry);

                byte[] bytes = System.Text.Encoding.Unicode.GetBytes(text.ToCharArray());

                zipOutputStream.Write(bytes, 0, bytes.Length);

                zipOutputStream.Flush();
                zipOutputStream.Finish();

                buffer      = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, Convert.ToInt32(ms.Length));
            }//using ( ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream( fileStreamOut ) ) ...

            return(ToBase64(buffer));
        }
Beispiel #5
0
        public static string CreateZIPFile(string path, int M, string strsuff)
        {
            try
            {
                Crc32 crc = new Crc32();//未压缩的
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipout = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(path + ".zip"));

                //ICSharpCode.SharpZipLib.GZip.GZipOutputStream zipout = new GZipOutputStream(System.IO.File.Create(path+ ".zip"));
                System.IO.FileStream fs = System.IO.File.OpenRead(path + strsuff);
                long   pai    = 1024 * 1024 * M;//每M兆写一次
                long   forint = fs.Length / pai + 1;
                byte[] buffer = null;
                zipout.SetLevel(7);
                ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(path + strsuff));
                entry.Size     = fs.Length;
                entry.DateTime = DateTime.Now;
                zipout.PutNextEntry(entry);
                //zipout.
                for (long i = 1; i <= forint; i++)
                {
                    if (pai * i < fs.Length)
                    {
                        buffer = new byte[pai];
                        fs.Seek(pai * (i - 1), System.IO.SeekOrigin.Begin);
                    }
                    else
                    {
                        if (fs.Length < pai)
                        {
                            buffer = new byte[fs.Length];
                        }
                        else
                        {
                            buffer = new byte[fs.Length - pai * (i - 1)];
                            fs.Seek(pai * (i - 1), System.IO.SeekOrigin.Begin);
                        }
                    }
                    fs.Read(buffer, 0, buffer.Length);
                    crc.Reset();
                    crc.Update(buffer);
                    zipout.Write(buffer, 0, buffer.Length);
                    zipout.Flush();
                }
                fs.Close();
                zipout.Finish();
                zipout.Close();

                System.IO.File.Delete(path + strsuff);
                // File.Create(path.Replace(".doc","") + ".zip",buffer.Length);
                return(path + ".zip");
            }
            catch (Exception ex)
            {
                string str = ex.Message;
                return(path);
            }
        }
Beispiel #6
0
        private void WriteToZipStream(ZipOutputStream zipOutputStream, IPolicySetCache set, bool runtime)
        {
            const int maxCompression = 9;
            zipOutputStream.SetLevel(maxCompression);

            AddZipEntryToZipOutputStream(zipOutputStream, WritePolicySetProperties(set, runtime), "properties.xml");

            AddOnePolicySetVersionASZipEntry(set.LatestVersion, zipOutputStream, runtime);

            zipOutputStream.Flush();
            zipOutputStream.Finish();
        }
Beispiel #7
0
 /// <summary>
 /// 压缩
 /// </summary>
 /// <param name="sourceBytes">待压缩数据</param>
 /// <returns></returns>
 public static byte[] Zip(byte[] sourceBytes)
 {
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zs = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms))
         {
             ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Code")
             {
                 DateTime = DateTime.Now
             };
             zs.PutNextEntry(entry);
             zs.Write(sourceBytes, 0, sourceBytes.Length);
             zs.Flush();
         }
         return(ms.ToArray());
     }
 }
Beispiel #8
0
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="dirPath">压缩目录(只压缩PDF文件)</param>
        /// <param name="zipFilePath">目标目录(如果为空,则以压缩目录为准)</param>
        /// <param name="error">异常信息</param>
        /// <returns></returns>
        public static bool ZipFile(string dirPath, string zipFilePath, out string error)
        {
            error = "";
            if (string.IsNullOrEmpty(dirPath) || !Directory.Exists(dirPath)) {
                error = "dirPath Error";
                return false;
            }

            if (string.IsNullOrEmpty(zipFilePath)) {
                if (dirPath.EndsWith("\\")) {
                    dirPath = dirPath.Substring(0, dirPath.Length - 1);
                }
                zipFilePath = dirPath + ".zip";
            }

            try {
                string[] fileNames = Directory.GetFiles(dirPath);
                using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath))) {
                    s.SetLevel(9);
                    byte[] buffer = new byte[4096];
                    foreach (string file in fileNames) {
                        if (Path.GetExtension(file).ToLower().Equals(".pdf")) {
                            ZipEntry entry = new ZipEntry(Path.GetFileName(file));
                            entry.DateTime = DateTime.Now;
                            s.PutNextEntry(entry);
                            using (FileStream fs = File.OpenRead(file)) {
                                int sourceBytes;
                                do {
                                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                    s.Write(buffer, 0, sourceBytes);
                                } while (sourceBytes > 0);
                            }
                        }
                    }
                    s.Flush();
                    s.Close();
                }
            } catch (Exception ex) {
                error = ex.Message.ToString();
                return false;
            }
            return true;
        }
Beispiel #9
0
        public ActionResult Download()
        {
            List<string> _lstFilePaths = new List<string>();
            _lstFilePaths.Add(@"C:\BrightVision\PdfReports\File1.pdf");
            _lstFilePaths.Add(@"C:\BrightVision\PdfReports\File2.pdf");
            _lstFilePaths.Add(@"C:\BrightVision\PdfReports\File3.pdf");
            _lstFilePaths.Add(@"C:\BrightVision\PdfReports\File4.pdf");
            _lstFilePaths.Add(@"C:\BrightVision\PdfReports\File5.pdf");
            _lstFilePaths.Add(@"C:\BrightVision\PdfReports\File6.pdf");
            _lstFilePaths.Add(@"C:\BrightVision\PdfReports\File7.pdf");
            _lstFilePaths.Add(@"C:\BrightVision\PdfReports\File8.pdf");

            Response.AddHeader("Content-Disposition", "attachment; filename=DemoZipFile.zip");
            Response.ContentType = "application/zip";

            using (ZipOutputStream _ZipStream = new ZipOutputStream(Response.OutputStream)) {
                foreach (string _filePath in _lstFilePaths) {
                    byte[] fileBytes = System.IO.File.ReadAllBytes(_filePath);
                    ZipEntry _fileEntry = new ZipEntry(Path.GetFileName(_filePath)) {
                        Size = fileBytes.Length
                    };

                    _ZipStream.PutNextEntry(_fileEntry);
                    _ZipStream.Write(fileBytes, 0, fileBytes.Length);
                    System.IO.File.Delete(_filePath);
                }

                _ZipStream.Flush();
                _ZipStream.Close();
            }

            return Content("<h2>Downloading File<h2>");

            //string _MimeType = BrightVision.Common.Utilities.FileManagerUtility.GetMimeType(_FilePath);
            //MemoryStream _ms = new MemoryStream(_Data);
            //return new FileStreamResult(_ms, _MimeType);
        }
        public void CompressImageBySharpZibLib(Stream compressStream,string compressFileName)
        {
            string saveZipFilePath = DateTime.Now.ToString("yyyyMMddhhmmss")+"zipfile";
            using (IsolatedStorageFile isolateFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var streamOut = new ZipOutputStream(isolateFile.OpenFile(saveZipFilePath,FileMode.Create)))
                {
                    streamOut.SetLevel(9);
                    var streamIn = compressStream;

                    string newName = ZipEntry.CleanName(compressFileName);
                    ZipEntry compressEntity = new ZipEntry(newName);

                    compressEntity.Size = compressStream.Length;
                    compressEntity.DateTime = DateTime.Now;
                    streamOut.PutNextEntry(compressEntity);
                    streamIn.CopyTo(streamOut);
                    streamOut.Flush();
                    streamOut.Finish();

                    var convertValue = ((float)streamOut.Length / (float)streamIn.Length) * 100 + "%";
                }
            }
        }
Beispiel #11
0
 public void Execute(string[] args, Reddit reddit)
 {
     if (args.Length != 3)
     {
         Console.WriteLine("Invalid usage. See 'srutil help backup' for more information.");
         return;
     }
     var subreddit = reddit.GetSubreddit(args[1]);
     using (var file = new ZipOutputStream(File.Create(args[2])))
     {
         file.SetLevel(5);
         var writer = new StreamWriter(file);
         writer.AutoFlush = true;
         var settings = subreddit.GetSettings();
         var serializer = new JsonSerializer();
         // Save settings
         Console.WriteLine("Saving settings...");
         var entry = new ZipEntry("settings.json");
         entry.DateTime = DateTime.Now;
         file.PutNextEntry(entry);
         serializer.Serialize(writer, settings);
         file.CloseEntry();
         // Save flair
         Console.WriteLine("Saving flair templates...");
         var flair = subreddit.GetUserFlairTemplates();
         entry = new ZipEntry("flair.json");
         file.PutNextEntry(entry);
         serializer.Serialize(writer, flair);
         file.CloseEntry();
         // Save styles
         Console.WriteLine("Saving CSS...");
         var styles = subreddit.GetStylesheet();
         entry = new ZipEntry("stylesheet.css");
         file.PutNextEntry(entry);
         writer.Write(styles.CSS);
         file.CloseEntry();
         // Save images
         Console.WriteLine("Saving images...");
         var webClient = new WebClient();
         var left = Console.CursorLeft; var top = Console.CursorTop;
         int progress = 1;
         foreach (var image in styles.Images)
         {
             var data = webClient.DownloadData(image.Url);
             entry = new ZipEntry("images/" + image.Name + Path.GetExtension(image.Url));
             file.PutNextEntry(entry);
             file.Write(data, 0, data.Length); file.Flush();
             file.CloseEntry();
             Console.CursorLeft = left; Console.CursorTop = top;
             Console.WriteLine("{0}/{1}", progress++, styles.Images.Count);
         }
         // Save header
         if (subreddit.HeaderImage != null)
         {
             Console.WriteLine("Saving header image...");
             var data = webClient.DownloadData(subreddit.HeaderImage);
             entry = new ZipEntry("header" + Path.GetExtension(subreddit.HeaderImage));
             file.PutNextEntry(entry);
             file.Write(data, 0, data.Length);
             file.CloseEntry();
         }
         Console.WriteLine("Done. {0} backed up to {1}.", subreddit.DisplayName, args[2]);
     }
 }
Beispiel #12
0
 public static clsResult WriteMemoryToZipEntryAndFlush(MemoryStream Memory, ZipOutputStream Stream)
 {
     clsResult result = new clsResult("Writing to zip stream");
     try
     {
         Memory.WriteTo(Stream);
         Memory.Flush();
         Stream.Flush();
         Stream.CloseEntry();
     }
     catch (Exception exception1)
     {
         ProjectData.SetProjectError(exception1);
         Exception exception = exception1;
         result.ProblemAdd(exception.Message);
         clsResult result2 = result;
         ProjectData.ClearProjectError();
         return result2;
     }
     return result;
 }
Beispiel #13
0
        public static void Zip(FileInfo file, byte[] key, string outputFolder, PercentChangedEventHandler percentChangedCallback)
        {
            if (string.IsNullOrEmpty(outputFolder))
                outputFolder = file.DirectoryName;

            FileStream inputStream = File.OpenRead(file.FullName);
            FileStream outputStream = File.OpenWrite(outputFolder + "\\" + file.Name + CRYPTOZIP_EXTENSION);

            Aes aes = new AesManaged();
            byte[] keyBytes = key;
            byte[] ivBytes = Encoding.UTF8.GetBytes(IV_STRING);

            using (CryptoStream cryptoStream = new CryptoStream(outputStream, aes.CreateEncryptor(keyBytes, ivBytes), CryptoStreamMode.Write))
            {
                using (ZipOutputStream zipOutputStream = new ZipOutputStream(cryptoStream))
                {
                    zipOutputStream.SetLevel(0);
                    zipOutputStream.UseZip64 = UseZip64.On;
                    ZipEntry zipEntry = new ZipEntry(file.Name);
                    zipEntry.DateTime = DateTime.Now;

                    zipOutputStream.PutNextEntry(zipEntry);
                    int read = 0;
                    byte[] buffer = new byte[4096];
                    double totalRead = 0;
                    double lastPercent = 0;

                    do
                    {
                        read = inputStream.Read(buffer, 0, buffer.Length);
                        zipOutputStream.Write(buffer, 0, read);

                        totalRead += read;
                        double percent = Math.Floor((totalRead / inputStream.Length) * 100);

                        if (percent > lastPercent)
                        {
                            lastPercent = percent;

                            if (percentChangedCallback != null)
                                percentChangedCallback(new PercentChangedEventArgs(percent));
                        }

                    } while (read == buffer.Length);

                    zipOutputStream.Finish();
                    zipOutputStream.Flush();
                }
            }
            inputStream.Close();
            outputStream.Close();
        }
 public bool ZipFiles(string inputFolderPath, string outputPathAndFile, string password)
 {
     try
        {
        ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
        int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
        // find number of chars to remove 	// from orginal file path
        TrimLength += 1; //remove '\'
        FileStream ostream;
        byte[] obuffer;
        //string outPath = inputFolderPath + @"\" + outputPathAndFile;
        string outPath = outputPathAndFile;
        using (ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)))
        {
            // create zip stream
            if (password != null && password != String.Empty)
                oZipStream.Password = password;
            oZipStream.SetLevel(9); // maximum compression
            ZipEntry oZipEntry;
            string file1 = "";
            string file2 = "";
            foreach (string file in ar) // for each file, generate a zipentry
            {
                oZipEntry = new ZipEntry(file.Remove(0, file.LastIndexOf('\\') + 1));
                oZipStream.PutNextEntry(oZipEntry);
                if (file1 == "") file1 = file; else file2 = file;
                if (!file.EndsWith(@"/")) // if a file ends with '/' its a directory
                {
                    ostream = File.OpenRead(file);
                    obuffer = new byte[ostream.Length];
                    ostream.Read(obuffer, 0, obuffer.Length);
                    oZipStream.Write(obuffer, 0, obuffer.Length);
                    oZipStream.Flush();
                    ostream.Flush();
                    ostream.Close();
                }
                oZipEntry = null;
            }
            oZipStream.Flush();
            oZipStream.Finish();
            oZipStream.Close();
        }
        }
        catch (Exception ex)
        {
        return false;
        }
        return true;
 }
Beispiel #15
0
 private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName)
 {
     bool flag = true;
     ZipEntry entry = null;
     FileStream stream = null;
     Crc32 crc = new Crc32();
     try
     {
         entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/"));
         s.PutNextEntry(entry);
         s.Flush();
         string[] files = Directory.GetFiles(FolderToZip);
         foreach (string str in files)
         {
             stream = File.OpenRead(str);
             byte[] buffer = new byte[stream.Length];
             stream.Read(buffer, 0, buffer.Length);
             entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(str)))
             {
                 DateTime = DateTime.Now,
                 Size = stream.Length
             };
             stream.Close();
             crc.Reset();
             crc.Update(buffer);
             entry.Crc = crc.Value;
             s.PutNextEntry(entry);
             s.Write(buffer, 0, buffer.Length);
         }
     }
     catch
     {
         flag = false;
     }
     finally
     {
         if (stream != null)
         {
             stream.Close();
             stream = null;
         }
         if (entry != null)
         {
             entry = null;
         }
         GC.Collect();
         GC.Collect(1);
     }
     string[] directories = Directory.GetDirectories(FolderToZip);
     foreach (string str2 in directories)
     {
         if (!ZipFileDictory(str2, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip))))
         {
             return false;
         }
     }
     return flag;
 }
Beispiel #16
0
        internal void Serialize(string filePath)
        {
            Stream stream = new MemoryStream();
            System.Windows.Forms.Cursor cursor = System.Windows.Forms.Cursor.Current;
            try
            {
                Serialize(stream, true);
                stream.Position = 0;

                byte[] buffer = new byte[8192];
                if (".xml".Equals(Path.GetExtension(filePath).ToLower()))
                {
            #if DEBUG
                    FileStream fWritter = File.Create(filePath);
                    StreamUtils.Copy(stream, fWritter, buffer);
                    fWritter.Close();
            #else
                    throw new Exception("XML format not supported by current version");
            #endif
                }
                else
                {
                    FileStream fs = File.Create(filePath);
                    BinaryFormatter bformatter = new BinaryFormatter();
                    bformatter.Serialize(fs, "version=7.14");
                    using (ZipOutputStream s = new ZipOutputStream(fs))
                    {
                        try
                        {
                            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
                            s.Password = "******";
                            if (model.HasResults)
                                s.SetLevel(5); // 0 (store only) to 9 (best compression)
                            else
                                s.SetLevel(9); // 0 (store only) to 9 (best compression)
                            ZipEntry entry = new ZipEntry(Path.GetFileName("[Empty]"));
                            s.PutNextEntry(entry);
                            StreamUtils.Copy(stream, s, buffer);
                        }
                        finally
                        {
                            s.Flush();
                            s.Finish();
                            s.Close();
                            s.Dispose();
                        }
                    }
                }
            }
            finally
            {
                stream.Close();
                System.Windows.Forms.Cursor.Current = cursor;
            }
        }
    /// <summary>
    /// Stores incomming data as standard zip file into byte array
    /// </summary>
    /// <param name="fileName">Filename</param>
    /// <param name="compressionLevel">Compression level 1-9</param>
    /// <returns>zip file as byte array</returns>
    private static byte[] ZipCompress(string fileName, int compressionLevel)
    {
        //SqlPipe pipe = SqlContext.Pipe;

        using (MemoryStream tempFileStream = new MemoryStream())
        using (ZipOutputStream zipOutput = new ZipOutputStream(tempFileStream))
        {
            zipOutput.SetLevel(compressionLevel);
            Crc32 crc = new Crc32();

            // Get local path and create stream to it.
            using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                // Read full stream to in-memory buffer.
                byte[] buffer = new byte[fileStream.Length];
                int offset = 0;
                int remaining = buffer.Length;
                while (remaining > 0)
                {
                    int read = fileStream.Read(buffer, offset, buffer.Length);
                    if (read <= 0)
                        throw new EndOfStreamException
                            (String.Format("End of stream reached with {0} bytes left to read", remaining));
                    remaining -= read;
                    offset += read;
                }

                //get crc to store in header.
                crc.Reset();
                crc.Update(buffer);

                // Create a new entry for the current file.
                ZipEntry entry = new ZipEntry(ZipEntry.CleanName(Path.GetFileName(fileName)))
                                     {
                                         DateTime = DateTime.Now,
                                         Size = fileStream.Length,
                                         Crc = crc.Value
                                     };
                fileStream.Close();

                zipOutput.PutNextEntry(entry);

                zipOutput.Write(buffer, 0, buffer.Length);
                // Finalize the zip output.
                zipOutput.Finish();
                // Flushes the create and close.
                zipOutput.Flush();
            }

            zipOutput.Close();
            //retrun zip compiant data stream
            return tempFileStream.ToArray();
        }
    }
Beispiel #18
0
        public ActionResult ServerBackup(string serverName)
        {
            var authres = CheckAuthorizationAndLog(Audit.AuditTypeEnum.View, true, serverName,"","", "backup server");
            if (authres != null)
                return authres;

            DNSManagement.Server msserver = new DNSManagement.Server(serverName, Session["Username"] as string, Session["Password"] as string);
            BackupModel bm = new BackupModel();
            bm.PopulateFromServer(msserver);
            //var res = bm.ToXml();
            var files = bm.ToConfigurationFiles();

            MemoryStream backupFile = new MemoryStream();
            ZipOutputStream zipBackup = new ZipOutputStream(backupFile);
            foreach (var file in files)
            {
                var data = System.Text.Encoding.UTF8.GetBytes(file.Value);
                if ((data.Length == 0) || (string.IsNullOrEmpty(file.Key)))
                    continue;

                ZipEntry entry = new ZipEntry(ZipEntry.CleanName(file.Key));
                entry.DateTime = DateTime.Now;
                entry.Size = data.Length;
                zipBackup.PutNextEntry(entry);
                zipBackup.Write(data, 0, data.Length);
                zipBackup.CloseEntry();
            }
            zipBackup.Flush();
            zipBackup.IsStreamOwner = false;
            zipBackup.Close();

            Response.ContentType = "application/zip";
            Response.AppendHeader("content-disposition", string.Format("attachment; filename=\"Backup_{0}_{1}.zip\"", serverName, DateTime.Now.ToString("yyyyMMddHHmmss")));
            Response.CacheControl = "Private";
            Response.Cache.SetExpires(DateTime.Now.AddMinutes(3)); // or put a timestamp in the filename in the content-disposition
            Response.OutputStream.Write(backupFile.ToArray(), 0, (int)backupFile.Length);
            Response.Flush();

            return new EmptyResult();

            //backup all settings to xml
            //backup all zones to bind files (?)
        }
Beispiel #19
0
    private void SaveBackground_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            string tmpdirectorypath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "tmp") + System.IO.Path.DirectorySeparatorChar;

            using (FileStream tempFileStream = new FileStream(ProjectSavePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
            {
                using (ZipOutputStream zipOutput = new ZipOutputStream(tempFileStream))
                {
                    // Zip with highest compression.
                    zipOutput.SetLevel(9);
                    zipOutput.SetComment(ProjectInfo.FileVersion.ToString());

                    //Project Data
                    string projfilename = SaveProject(tmpdirectorypath);
                    using (FileStream fileStream = new FileStream(projfilename, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // Read full stream to in-memory buffer.
                        byte[] buffer = new byte[fileStream.Length];
                        fileStream.Read(buffer, 0, buffer.Length);

                        // Create a new entry for the current file.
                        ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(projfilename));
                        entry.DateTime = DateTime.Now;
                        entry.Size = fileStream.Length;
                        entry.Comment = "Main";
                        fileStream.Close();
                        zipOutput.PutNextEntry(entry);
                        zipOutput.Write(buffer, 0, buffer.Length);
                        buffer = null;
                    }

                    //Thumbs
                    string[] thumbs = Directory.GetFiles(Thumbpath);
                    for (int i = 0; i < thumbs.Length; i++)
                    {
                        using (FileStream fileStream = new FileStream(thumbs[i], FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            // Read full stream to in-memory buffer.
                            byte[] buffer = new byte[fileStream.Length];
                            fileStream.Read(buffer, 0, buffer.Length);

                            // Create a new entry for the current file.
                            ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(thumbs[i]));
                            entry.DateTime = DateTime.Now;
                            entry.Size = fileStream.Length;
                            entry.Comment = "Thumb";
                            fileStream.Close();
                            zipOutput.PutNextEntry(entry);
                            zipOutput.Write(buffer, 0, buffer.Length);
                            buffer = null;
                        }
                    }

                    zipOutput.Finish();
                    zipOutput.Flush();
                    zipOutput.Close();
                }
            }

            Directory.Delete(tmpdirectorypath, true);

            ProjectSaved = true;
            e.Result = true;
        }
        catch (Exception ex)
        {
            e.Result = false;
            ThreadException = ex;
        }
    }
		} // proc CloseZipStream

		private void ZipFileItem(CmdletNotify notify, CmdletProgress bar, Stream src, ZipOutputStream zip, FileIndexItem item)
		{
			var entry = new ZipEntry(ZipEntry.CleanName(item.RelativePath));

			entry.DateTime = item.LastWriteTimeUtc;
			entry.Size = src.Length;
			entry.Comment = item.GetComment();
			entry.CompressionMethod = ZipFile(item.RelativePath) ? CompressionMethod.Deflated : CompressionMethod.Stored;
			zip.PutNextEntry(entry);

			Stuff.CopyRawBytes(bar, item.RelativePath, src.Length, src, zip);

			zip.CloseEntry();
			zip.Flush();
		} // proc ZipFileItem
		} // proc CreateZipStream

		private void CloseZipStream(FileWrite zipStream, ZipOutputStream zip)
		{
			if (zip != null)
			{
				zip.Flush();
				zip.Dispose();
			}
			if (zipStream != null)
				zipStream.Dispose();
		} // proc CloseZipStream
Beispiel #22
0
        public clsResult Write_WZ(sWrite_WZ_Args Args)
        {
            clsResult ReturnResult =
                new clsResult("Compiling to " + Convert.ToString(ControlChars.Quote) + Args.Path + Convert.ToString(ControlChars.Quote));

            try
            {
                switch ( Args.CompileType )
                {
                    case sWrite_WZ_Args.enumCompileType.Multiplayer:
                        if ( Args.Multiplayer == null )
                        {
                            ReturnResult.ProblemAdd("Multiplayer arguments were not passed.");
                            return ReturnResult;
                        }
                        if ( Args.Multiplayer.PlayerCount < 2 | Args.Multiplayer.PlayerCount > 10 )
                        {
                            ReturnResult.ProblemAdd("Number of players was below 2 or above 10.");
                            return ReturnResult;
                        }
                        if ( !Args.Multiplayer.IsBetaPlayerFormat )
                        {
                            if ( !(Args.Multiplayer.PlayerCount == 2 | Args.Multiplayer.PlayerCount == 4 | Args.Multiplayer.PlayerCount == 8) )
                            {
                                ReturnResult.ProblemAdd("Number of players was not 2, 4 or 8 in original format.");
                                return ReturnResult;
                            }
                        }
                        break;
                    case sWrite_WZ_Args.enumCompileType.Campaign:
                        if ( Args.Campaign == null )
                        {
                            ReturnResult.ProblemAdd("Campaign arguments were not passed.");
                            return ReturnResult;
                        }
                        break;
                    default:
                        ReturnResult.ProblemAdd("Unknown compile method.");
                        return ReturnResult;
                }

                if ( !Args.Overwrite )
                {
                    if ( File.Exists(Args.Path) )
                    {
                        ReturnResult.ProblemAdd("The selected file already exists.");
                        return ReturnResult;
                    }
                }

                char Quote = ControlChars.Quote;
                char EndChar = '\n';
                string Text = "";

                MemoryStream File_LEV_Memory = new MemoryStream();
                StreamWriter File_LEV = new StreamWriter(File_LEV_Memory, App.UTF8Encoding);
                MemoryStream File_MAP_Memory = new MemoryStream();
                BinaryWriter File_MAP = new BinaryWriter(File_MAP_Memory, App.ASCIIEncoding);
                MemoryStream File_GAM_Memory = new MemoryStream();
                BinaryWriter File_GAM = new BinaryWriter(File_GAM_Memory, App.ASCIIEncoding);
                MemoryStream File_featBJO_Memory = new MemoryStream();
                BinaryWriter File_featBJO = new BinaryWriter(File_featBJO_Memory, App.ASCIIEncoding);
                MemoryStream INI_feature_Memory = new MemoryStream();
                IniWriter INI_feature = IniWriter.CreateFile(INI_feature_Memory);
                MemoryStream File_TTP_Memory = new MemoryStream();
                BinaryWriter File_TTP = new BinaryWriter(File_TTP_Memory, App.ASCIIEncoding);
                MemoryStream File_structBJO_Memory = new MemoryStream();
                BinaryWriter File_structBJO = new BinaryWriter(File_structBJO_Memory, App.ASCIIEncoding);
                MemoryStream INI_struct_Memory = new MemoryStream();
                IniWriter INI_struct = IniWriter.CreateFile(INI_struct_Memory);
                MemoryStream File_droidBJO_Memory = new MemoryStream();
                BinaryWriter File_droidBJO = new BinaryWriter(File_droidBJO_Memory, App.ASCIIEncoding);
                MemoryStream INI_droid_Memory = new MemoryStream();
                IniWriter INI_droid = IniWriter.CreateFile(INI_droid_Memory);
                MemoryStream INI_Labels_Memory = new MemoryStream();
                IniWriter INI_Labels = IniWriter.CreateFile(INI_Labels_Memory);

                string PlayersPrefix = "";
                string PlayersText = "";

                if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Multiplayer )
                {
                    PlayersText = IOUtil.InvariantToString(Args.Multiplayer.PlayerCount);
                    PlayersPrefix = PlayersText + "c-";
                    string fog = "";
                    string TilesetNum = "";
                    if ( Tileset == null )
                    {
                        ReturnResult.ProblemAdd("Map must have a tileset.");
                        return ReturnResult;
                    }
                    else if ( Tileset == App.Tileset_Arizona )
                    {
                        fog = "fog1.wrf";
                        TilesetNum = "1";
                    }
                    else if ( Tileset == App.Tileset_Urban )
                    {
                        fog = "fog2.wrf";
                        TilesetNum = "2";
                    }
                    else if ( Tileset == App.Tileset_Rockies )
                    {
                        fog = "fog3.wrf";
                        TilesetNum = "3";
                    }
                    else
                    {
                        ReturnResult.ProblemAdd("Unknown tileset selected.");
                        return ReturnResult;
                    }

                    Text = "// Made with " + Constants.ProgramName + " " + Constants.ProgramVersionNumber + " " + Constants.ProgramPlatform +
                           Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    DateTime DateNow = DateTime.Now;
                    Text = "// Date: " + Convert.ToString(DateNow.Year) + "/" + App.MinDigits(DateNow.Month, 2) + "/" +
                           App.MinDigits(DateNow.Day, 2) + " " + App.MinDigits(DateNow.Hour, 2) + ":" + App.MinDigits(DateNow.Minute, 2) + ":" +
                           App.MinDigits(DateNow.Second, 2) + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "// Author: " + Args.Multiplayer.AuthorName + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "// License: " + Args.Multiplayer.License + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = EndChar.ToString();
                    File_LEV.Write(Text);
                    Text = "level   " + Args.MapName + "-T1" + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "players " + PlayersText + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "type    14" + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "dataset MULTI_CAM_" + TilesetNum + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "game    " + Convert.ToString(Quote) + "multiplay/maps/" + PlayersPrefix + Args.MapName + ".gam" + Convert.ToString(Quote) +
                           Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "data    " + Convert.ToString(Quote) + "wrf/multi/skirmish" + PlayersText + ".wrf" + Convert.ToString(Quote) +
                           Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "data    " + Convert.ToString(Quote) + "wrf/multi/" + fog + Convert.ToString(Quote) + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = EndChar.ToString();
                    File_LEV.Write(Text);
                    Text = "level   " + Args.MapName + "-T2" + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "players " + PlayersText + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "type    18" + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "dataset MULTI_T2_C" + TilesetNum + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "game    " + Convert.ToString(Quote) + "multiplay/maps/" + PlayersPrefix + Args.MapName + ".gam" + Convert.ToString(Quote) +
                           Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "data    " + Convert.ToString(Quote) + "wrf/multi/t2-skirmish" + PlayersText + ".wrf" + Convert.ToString(Quote) +
                           Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "data    " + Convert.ToString(Quote) + "wrf/multi/" + fog + Convert.ToString(Quote) + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = EndChar.ToString();
                    File_LEV.Write(Text);
                    Text = "level   " + Args.MapName + "-T3" + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "players " + PlayersText + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "type    19" + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "dataset MULTI_T3_C" + TilesetNum + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "game    " + Convert.ToString(Quote) + "multiplay/maps/" + PlayersPrefix + Args.MapName + ".gam" + Convert.ToString(Quote) +
                           Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "data    " + Convert.ToString(Quote) + "wrf/multi/t3-skirmish" + PlayersText + ".wrf" + Convert.ToString(Quote) +
                           Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                    Text = "data    " + Convert.ToString(Quote) + "wrf/multi/" + fog + Convert.ToString(Quote) + Convert.ToString(EndChar);
                    File_LEV.Write(Text);
                }

                byte[] GameZeroBytes = new byte[20];

                IOUtil.WriteText(File_GAM, false, "game");
                File_GAM.Write(8U);
                File_GAM.Write(0U); //Time
                if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Multiplayer )
                {
                    File_GAM.Write(0U);
                }
                else if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Campaign )
                {
                    File_GAM.Write(Args.Campaign.GAMType);
                }
                File_GAM.Write(Args.ScrollMin.X);
                File_GAM.Write(Args.ScrollMin.Y);
                File_GAM.Write(Args.ScrollMax.X);
                File_GAM.Write(Args.ScrollMax.Y);
                File_GAM.Write(GameZeroBytes);

                int A = 0;
                int X = 0;
                int Y = 0;

                IOUtil.WriteText(File_MAP, false, "map ");
                File_MAP.Write(10U);
                File_MAP.Write(Convert.ToBoolean((uint)Terrain.TileSize.X));
                File_MAP.Write(Convert.ToBoolean((uint)Terrain.TileSize.Y));
                byte Flip = 0;
                byte Rotation = 0;
                bool DoFlipX = default(bool);
                int InvalidTileCount = 0;
                int TextureNum = 0;
                for ( Y = 0; Y <= Terrain.TileSize.Y - 1; Y++ )
                {
                    for ( X = 0; X <= Terrain.TileSize.X - 1; X++ )
                    {
                        TileUtil.TileOrientation_To_OldOrientation(Terrain.Tiles[X, Y].Texture.Orientation, ref Rotation, ref DoFlipX);
                        Flip = (byte)0;
                        if ( Terrain.Tiles[X, Y].Tri )
                        {
                            Flip += (byte)8;
                        }
                        Flip += (byte)(Rotation * 16);
                        if ( DoFlipX )
                        {
                            Flip += (byte)128;
                        }
                        TextureNum = Terrain.Tiles[X, Y].Texture.TextureNum;
                        if ( TextureNum < 0 | TextureNum > 255 )
                        {
                            TextureNum = 0;
                            if ( InvalidTileCount < 16 )
                            {
                                ReturnResult.WarningAdd("Tile texture number " + Convert.ToString(Terrain.Tiles[X, Y].Texture.TextureNum) +
                                                        " is invalid on tile " + Convert.ToString(X) + ", " + Convert.ToString(Y) +
                                                        " and was compiled as texture number " + Convert.ToString(TextureNum) + ".");
                            }
                            InvalidTileCount++;
                        }
                        File_MAP.Write((byte)TextureNum);
                        File_MAP.Write(Flip);
                        File_MAP.Write(Convert.ToBoolean(Terrain.Vertices[X, Y].Height));
                    }
                }
                if ( InvalidTileCount > 0 )
                {
                    ReturnResult.WarningAdd(InvalidTileCount + " tile texture numbers were invalid.");
                }
                File_MAP.Write(1U); //gateway version
                File_MAP.Write(Convert.ToBoolean((uint)Gateways.Count));
                clsGateway Gateway = default(clsGateway);
                foreach ( clsGateway tempLoopVar_Gateway in Gateways )
                {
                    Gateway = tempLoopVar_Gateway;
                    File_MAP.Write((byte)(MathUtil.Clamp_int(Gateway.PosA.X, 0, 255)));
                    File_MAP.Write((byte)(MathUtil.Clamp_int(Gateway.PosA.Y, 0, 255)));
                    File_MAP.Write((byte)(MathUtil.Clamp_int(Gateway.PosB.X, 0, 255)));
                    File_MAP.Write((byte)(MathUtil.Clamp_int(Gateway.PosB.Y, 0, 255)));
                }

                clsFeatureType FeatureType = default(clsFeatureType);
                clsStructureType StructureType = default(clsStructureType);
                clsDroidDesign DroidType = default(clsDroidDesign);
                clsDroidTemplate DroidTemplate = default(clsDroidTemplate);
                clsUnit Unit = default(clsUnit);
                clsStructureWriteWZ StructureWrite = new clsStructureWriteWZ();
                StructureWrite.File = File_structBJO;
                StructureWrite.CompileType = Args.CompileType;
                if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Multiplayer )
                {
                    StructureWrite.PlayerCount = Args.Multiplayer.PlayerCount;
                }
                else
                {
                    StructureWrite.PlayerCount = 0;
                }

                byte[] FeatZeroBytes = new byte[12];

                IOUtil.WriteText(File_featBJO, false, "feat");
                File_featBJO.Write(8U);
                clsObjectPriorityOrderList FeatureOrder = new clsObjectPriorityOrderList();
                foreach ( clsUnit tempLoopVar_Unit in Units )
                {
                    Unit = tempLoopVar_Unit;
                    if ( Unit.Type.Type == clsUnitType.enumType.Feature )
                    {
                        FeatureOrder.SetItem(Unit);
                        FeatureOrder.ActionPerform();
                    }
                }
                File_featBJO.Write(Convert.ToBoolean((uint)FeatureOrder.Result.Count));
                for ( A = 0; A <= FeatureOrder.Result.Count - 1; A++ )
                {
                    Unit = FeatureOrder.Result[A];
                    FeatureType = (clsFeatureType)Unit.Type;
                    IOUtil.WriteTextOfLength(File_featBJO, 40, FeatureType.Code);
                    File_featBJO.Write(Unit.ID);
                    File_featBJO.Write(Convert.ToBoolean((uint)Unit.Pos.Horizontal.X));
                    File_featBJO.Write(Convert.ToBoolean((uint)Unit.Pos.Horizontal.Y));
                    File_featBJO.Write(Convert.ToBoolean((uint)Unit.Pos.Altitude));
                    File_featBJO.Write(Convert.ToBoolean((uint)Unit.Rotation));
                    switch ( Args.CompileType )
                    {
                        case sWrite_WZ_Args.enumCompileType.Multiplayer:
                            File_featBJO.Write(Unit.GetBJOMultiplayerPlayerNum(Args.Multiplayer.PlayerCount));
                            break;
                        case sWrite_WZ_Args.enumCompileType.Campaign:
                            File_featBJO.Write(Unit.GetBJOCampaignPlayerNum());
                            break;
                        default:
                            Debugger.Break();
                            break;
                    }
                    File_featBJO.Write(FeatZeroBytes);
                }

                IOUtil.WriteText(File_TTP, false, "ttyp");
                File_TTP.Write(8U);
                File_TTP.Write(Convert.ToBoolean((uint)Tileset.TileCount));
                for ( A = 0; A <= Tileset.TileCount - 1; A++ )
                {
                    File_TTP.Write(Convert.ToBoolean(Tile_TypeNum[A]));
                }

                IOUtil.WriteText(File_structBJO, false, "stru");
                File_structBJO.Write(8U);
                clsObjectPriorityOrderList NonModuleStructureOrder = new clsObjectPriorityOrderList();
                //non-module structures
                foreach ( clsUnit tempLoopVar_Unit in Units )
                {
                    Unit = tempLoopVar_Unit;
                    if ( Unit.Type.Type == clsUnitType.enumType.PlayerStructure )
                    {
                        StructureType = (clsStructureType)Unit.Type;
                        if ( !StructureType.IsModule() )
                        {
                            NonModuleStructureOrder.SetItem(Unit);
                            NonModuleStructureOrder.ActionPerform();
                        }
                    }
                }
                clsObjectPriorityOrderList ModuleStructureOrder = new clsObjectPriorityOrderList();
                //module structures
                foreach ( clsUnit tempLoopVar_Unit in Units )
                {
                    Unit = tempLoopVar_Unit;
                    if ( Unit.Type.Type == clsUnitType.enumType.PlayerStructure )
                    {
                        StructureType = (clsStructureType)Unit.Type;
                        if ( StructureType.IsModule() )
                        {
                            ModuleStructureOrder.SetItem(Unit);
                            ModuleStructureOrder.ActionPerform();
                        }
                    }
                }
                File_structBJO.Write(Convert.ToBoolean((uint)(NonModuleStructureOrder.Result.Count + ModuleStructureOrder.Result.Count)));
                NonModuleStructureOrder.Result.PerformTool(StructureWrite);
                ModuleStructureOrder.Result.PerformTool(StructureWrite);

                byte[] DintZeroBytes = new byte[12];

                IOUtil.WriteText(File_droidBJO, false, "dint");
                File_droidBJO.Write(8U);
                clsObjectPriorityOrderList Droids = new clsObjectPriorityOrderList();
                foreach ( clsUnit tempLoopVar_Unit in Units )
                {
                    Unit = tempLoopVar_Unit;
                    if ( Unit.Type.Type == clsUnitType.enumType.PlayerDroid )
                    {
                        DroidType = (clsDroidDesign)Unit.Type;
                        if ( DroidType.IsTemplate )
                        {
                            Droids.SetItem(Unit);
                            Droids.ActionPerform();
                        }
                    }
                }
                File_droidBJO.Write(Convert.ToBoolean((uint)Droids.Result.Count));
                for ( A = 0; A <= Droids.Result.Count - 1; A++ )
                {
                    Unit = Droids.Result[A];
                    DroidTemplate = (clsDroidTemplate)Unit.Type;
                    IOUtil.WriteTextOfLength(File_droidBJO, 40, DroidTemplate.Code);
                    File_droidBJO.Write(Unit.ID);
                    File_droidBJO.Write(Convert.ToBoolean((uint)Unit.Pos.Horizontal.X));
                    File_droidBJO.Write(Convert.ToBoolean((uint)Unit.Pos.Horizontal.Y));
                    File_droidBJO.Write(Convert.ToBoolean((uint)Unit.Pos.Altitude));
                    File_droidBJO.Write(Convert.ToBoolean((uint)Unit.Rotation));
                    switch ( Args.CompileType )
                    {
                        case sWrite_WZ_Args.enumCompileType.Multiplayer:
                            File_droidBJO.Write(Unit.GetBJOMultiplayerPlayerNum(Args.Multiplayer.PlayerCount));
                            break;
                        case sWrite_WZ_Args.enumCompileType.Campaign:
                            File_droidBJO.Write(Unit.GetBJOCampaignPlayerNum());
                            break;
                        default:
                            Debugger.Break();
                            break;
                    }
                    File_droidBJO.Write(DintZeroBytes);
                }

                ReturnResult.Add(Serialize_WZ_FeaturesINI(INI_feature));
                if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Multiplayer )
                {
                    ReturnResult.Add(Serialize_WZ_StructuresINI(INI_struct, Args.Multiplayer.PlayerCount));
                    ReturnResult.Add(Serialize_WZ_DroidsINI(INI_droid, Args.Multiplayer.PlayerCount));
                    ReturnResult.Add(Serialize_WZ_LabelsINI(INI_Labels, Args.Multiplayer.PlayerCount));
                }
                else if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Campaign )
                {
                    ReturnResult.Add(Serialize_WZ_StructuresINI(INI_struct, -1));
                    ReturnResult.Add(Serialize_WZ_DroidsINI(INI_droid, -1));
                    ReturnResult.Add(Serialize_WZ_LabelsINI(INI_Labels, 0)); //interprets -1 players as an FMap
                }

                File_LEV.Flush();
                File_MAP.Flush();
                File_GAM.Flush();
                File_featBJO.Flush();
                INI_feature.File.Flush();
                File_TTP.Flush();
                File_structBJO.Flush();
                INI_struct.File.Flush();
                File_droidBJO.Flush();
                INI_droid.File.Flush();
                INI_Labels.File.Flush();

                if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Multiplayer )
                {
                    if ( !Args.Overwrite )
                    {
                        if ( File.Exists(Args.Path) )
                        {
                            ReturnResult.ProblemAdd("A file already exists at: " + Args.Path);
                            return ReturnResult;
                        }
                    }
                    else
                    {
                        if ( File.Exists(Args.Path) )
                        {
                            try
                            {
                                File.Delete(Args.Path);
                            }
                            catch ( Exception ex )
                            {
                                ReturnResult.ProblemAdd("Unable to delete existing file: " + ex.Message);
                                return ReturnResult;
                            }
                        }
                    }

                    ZipOutputStream WZStream = default(ZipOutputStream);

                    try
                    {
                        WZStream = new ZipOutputStream(File.Create(Args.Path));
                    }
                    catch ( Exception ex )
                    {
                        ReturnResult.ProblemAdd(ex.Message);
                        return ReturnResult;
                    }

                    WZStream.SetLevel(9);
                    WZStream.UseZip64 = UseZip64.Off; //warzone crashes without this

                    try
                    {
                        string ZipPath = "";
                        ZipEntry ZipEntry = default(ZipEntry);

                        if ( Args.Multiplayer.IsBetaPlayerFormat )
                        {
                            ZipPath = PlayersPrefix + Args.MapName + ".xplayers.lev";
                        }
                        else
                        {
                            ZipPath = PlayersPrefix + Args.MapName + ".addon.lev";
                        }
                        ZipEntry = IOUtil.ZipMakeEntry(WZStream, ZipPath, ReturnResult);
                        if ( ZipEntry != null )
                        {
                            File_LEV_Memory.WriteTo(WZStream);
                            WZStream.Flush();
                            WZStream.CloseEntry();
                        }

                        ZipEntry = new ZipEntry("multiplay/");
                        WZStream.PutNextEntry(ZipEntry);
                        ZipEntry = new ZipEntry("multiplay/maps/");
                        WZStream.PutNextEntry(ZipEntry);
                        ZipEntry = new ZipEntry("multiplay/maps/" + PlayersPrefix + Args.MapName + "/");
                        WZStream.PutNextEntry(ZipEntry);

                        ZipPath = "multiplay/maps/" + PlayersPrefix + Args.MapName + ".gam";
                        ZipEntry = IOUtil.ZipMakeEntry(WZStream, ZipPath, ReturnResult);
                        if ( ZipEntry != null )
                        {
                            ReturnResult.Add(IOUtil.WriteMemoryToZipEntryAndFlush(File_GAM_Memory, WZStream));
                        }
                        else
                        {
                            ReturnResult.ProblemAdd("Unable to make entry " + ZipPath);
                        }

                        ZipPath = "multiplay/maps/" + PlayersPrefix + Args.MapName + "/" + "dinit.bjo";
                        ZipEntry = IOUtil.ZipMakeEntry(WZStream, ZipPath, ReturnResult);
                        if ( ZipEntry != null )
                        {
                            ReturnResult.Add(IOUtil.WriteMemoryToZipEntryAndFlush(File_droidBJO_Memory, WZStream));
                        }
                        else
                        {
                            ReturnResult.ProblemAdd("Unable to make entry " + ZipPath);
                        }

                        ZipPath = "multiplay/maps/" + PlayersPrefix + Args.MapName + "/" + "droid.ini";
                        ZipEntry = IOUtil.ZipMakeEntry(WZStream, ZipPath, ReturnResult);
                        if ( ZipEntry != null )
                        {
                            ReturnResult.Add(IOUtil.WriteMemoryToZipEntryAndFlush(INI_droid_Memory, WZStream));
                        }
                        else
                        {
                            ReturnResult.ProblemAdd("Unable to make entry " + ZipPath);
                        }

                        ZipPath = "multiplay/maps/" + PlayersPrefix + Args.MapName + "/" + "feat.bjo";
                        ZipEntry = IOUtil.ZipMakeEntry(WZStream, ZipPath, ReturnResult);
                        if ( ZipEntry != null )
                        {
                            ReturnResult.Add(IOUtil.WriteMemoryToZipEntryAndFlush(File_featBJO_Memory, WZStream));
                        }
                        else
                        {
                            ReturnResult.ProblemAdd("Unable to make entry " + ZipPath);
                        }

                        ZipPath = "multiplay/maps/" + PlayersPrefix + Args.MapName + "/" + "feature.ini";
                        ZipEntry = IOUtil.ZipMakeEntry(WZStream, ZipPath, ReturnResult);
                        if ( ZipEntry != null )
                        {
                            ReturnResult.Add(IOUtil.WriteMemoryToZipEntryAndFlush(INI_feature_Memory, WZStream));
                        }
                        else
                        {
                            ReturnResult.ProblemAdd("Unable to make entry " + ZipPath);
                        }

                        ZipPath = "multiplay/maps/" + PlayersPrefix + Args.MapName + "/" + "game.map";
                        ZipEntry = IOUtil.ZipMakeEntry(WZStream, ZipPath, ReturnResult);
                        if ( ZipEntry != null )
                        {
                            ReturnResult.Add(IOUtil.WriteMemoryToZipEntryAndFlush(File_MAP_Memory, WZStream));
                        }
                        else
                        {
                            ReturnResult.ProblemAdd("Unable to make entry " + ZipPath);
                        }

                        ZipPath = "multiplay/maps/" + PlayersPrefix + Args.MapName + "/" + "struct.bjo";
                        ZipEntry = IOUtil.ZipMakeEntry(WZStream, ZipPath, ReturnResult);
                        if ( ZipEntry != null )
                        {
                            ReturnResult.Add(IOUtil.WriteMemoryToZipEntryAndFlush(File_structBJO_Memory, WZStream));
                        }
                        else
                        {
                            ReturnResult.ProblemAdd("Unable to make entry " + ZipPath);
                        }

                        ZipPath = "multiplay/maps/" + PlayersPrefix + Args.MapName + "/" + "struct.ini";
                        ZipEntry = IOUtil.ZipMakeEntry(WZStream, ZipPath, ReturnResult);
                        if ( ZipEntry != null )
                        {
                            ReturnResult.Add(IOUtil.WriteMemoryToZipEntryAndFlush(INI_struct_Memory, WZStream));
                        }
                        else
                        {
                            ReturnResult.ProblemAdd("Unable to make entry " + ZipPath);
                        }

                        ZipPath = "multiplay/maps/" + PlayersPrefix + Args.MapName + "/" + "ttypes.ttp";
                        ZipEntry = IOUtil.ZipMakeEntry(WZStream, ZipPath, ReturnResult);
                        if ( ZipEntry != null )
                        {
                            ReturnResult.Add(IOUtil.WriteMemoryToZipEntryAndFlush(File_TTP_Memory, WZStream));
                        }
                        else
                        {
                            ReturnResult.ProblemAdd("Unable to make entry " + ZipPath);
                        }

                        if ( INI_Labels_Memory.Length > 0 )
                        {
                            ZipPath = "multiplay/maps/" + PlayersPrefix + Args.MapName + "/" + "labels.ini";
                            ZipEntry = IOUtil.ZipMakeEntry(WZStream, ZipPath, ReturnResult);
                            if ( ZipEntry != null )
                            {
                                ReturnResult.Add(IOUtil.WriteMemoryToZipEntryAndFlush(INI_Labels_Memory, WZStream));
                            }
                            else
                            {
                                ReturnResult.ProblemAdd("Unable to make entry " + ZipPath);
                            }
                        }

                        WZStream.Finish();
                        WZStream.Close();
                        return ReturnResult;
                    }
                    catch ( Exception ex )
                    {
                        WZStream.Close();
                        ReturnResult.ProblemAdd(ex.Message);
                        return ReturnResult;
                    }
                }
                else if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Campaign )
                {
                    string CampDirectory = App.EndWithPathSeperator(Args.Path);

                    if ( !Directory.Exists(CampDirectory) )
                    {
                        ReturnResult.ProblemAdd("Directory " + CampDirectory + " does not exist.");
                        return ReturnResult;
                    }

                    string FilePath = "";

                    FilePath = CampDirectory + Args.MapName + ".gam";
                    ReturnResult.Add(IOUtil.WriteMemoryToNewFile(File_GAM_Memory, CampDirectory + Args.MapName + ".gam"));

                    CampDirectory += Args.MapName + Convert.ToString(App.PlatformPathSeparator);
                    try
                    {
                        Directory.CreateDirectory(CampDirectory);
                    }
                    catch ( Exception )
                    {
                        ReturnResult.ProblemAdd("Unable to create directory " + CampDirectory);
                        return ReturnResult;
                    }

                    FilePath = CampDirectory + "dinit.bjo";
                    ReturnResult.Add(IOUtil.WriteMemoryToNewFile(File_droidBJO_Memory, FilePath));

                    FilePath = CampDirectory + "droid.ini";
                    ReturnResult.Add(IOUtil.WriteMemoryToNewFile(INI_droid_Memory, FilePath));

                    FilePath = CampDirectory + "feat.bjo";
                    ReturnResult.Add(IOUtil.WriteMemoryToNewFile(File_featBJO_Memory, FilePath));

                    FilePath = CampDirectory + "feature.ini";
                    ReturnResult.Add(IOUtil.WriteMemoryToNewFile(INI_feature_Memory, FilePath));

                    FilePath = CampDirectory + "game.map";
                    ReturnResult.Add(IOUtil.WriteMemoryToNewFile(File_MAP_Memory, FilePath));

                    FilePath = CampDirectory + "struct.bjo";
                    ReturnResult.Add(IOUtil.WriteMemoryToNewFile(File_structBJO_Memory, FilePath));

                    FilePath = CampDirectory + "struct.ini";
                    ReturnResult.Add(IOUtil.WriteMemoryToNewFile(INI_struct_Memory, FilePath));

                    FilePath = CampDirectory + "ttypes.ttp";
                    ReturnResult.Add(IOUtil.WriteMemoryToNewFile(File_TTP_Memory, FilePath));

                    FilePath = CampDirectory + "labels.ini";
                    ReturnResult.Add(IOUtil.WriteMemoryToNewFile(INI_Labels_Memory, FilePath));
                }
            }
            catch ( Exception ex )
            {
                Debugger.Break();
                ReturnResult.ProblemAdd(ex.Message);
                return ReturnResult;
            }

            return ReturnResult;
        }
Beispiel #23
0
		private void btnExport_Click(object sender, EventArgs e)
		{
			string tmpf = Path.GetTempFileName() + ".zip";
			using (var stream = new FileStream(tmpf,FileMode.Create,FileAccess.Write,FileShare.Read))
			{
				var zip = new ZipOutputStream(stream)
				{
					IsStreamOwner = false,
					UseZip64 = UseZip64.Off
				};

				foreach (var entry in PSGEntries)
				{
					var ze = new ZipEntry(entry.name + ".wav") { CompressionMethod = CompressionMethod.Deflated };
					zip.PutNextEntry(ze);
					var ms = new MemoryStream();
					var bw = new BinaryWriter(ms);
					bw.Write(emptyWav, 0, emptyWav.Length);
					ms.Position = 0x18; //samplerate and avgbytespersecond
					bw.Write(20000);
					bw.Write(20000 * 2);
					bw.Flush();
					ms.Position = 0x2C;
					for (int i = 0; i < 32; i++)
						for(int j=0;j<16;j++)
							bw.Write(entry.waveform[i]);
					bw.Flush();
					var buf = ms.GetBuffer();
					zip.Write(buf, 0, (int)ms.Length);
					zip.Flush();
					zip.CloseEntry();
				}
				zip.Close();
				stream.Flush();
			}
			System.Diagnostics.Process.Start(tmpf);
		}
Beispiel #24
0
        /// <summary>
        /// Compresses all files in the given folder using sharpziplib
        /// 
        /// http://stackoverflow.com/questions/1679986/zip-file-created-with-sharpziplib-cannot-be-opened-on-mac-os-x
        /// 
        /// </summary>
        /// <param name='folder'>
        /// Folder.
        /// </param>
        /// <param name='outputfile'>
        /// name of the zip
        /// </param>
        public static void CompressFolder(String folder, String outputfile)
        {
            DirectoryInfo di = new DirectoryInfo(folder);

            if (di.Exists)
            {
                FileInfo[] files = di.GetFiles();
                using (var outStream = new FileStream(outputfile, FileMode.Create))
                {
                    using (var zipStream = new ZipOutputStream(outStream))
                    {
                        Crc32 crc = new Crc32();

                        foreach (FileInfo fi in files)
                        {
                            byte[] buffer = File.ReadAllBytes(fi.FullName);

                            ZipEntry entry = new ZipEntry(fi.Name);
                            entry.DateTime = fi.LastWriteTime;
                            entry.Size = buffer.Length;

                            crc.Reset();
                            crc.Update(buffer);

                            entry.Crc = crc.Value;

                            zipStream.PutNextEntry(entry);
                            zipStream.Write(buffer, 0, buffer.Length);
                        }

                        zipStream.Finish();

                        // I dont think this is required at all
                        zipStream.Flush();
                        zipStream.Close();
                    }
                }
            } else
            {
                throw new Exception("the folder " + folder + " does not exist");
            }
        }
        }// ZipFile

        /// <summary>
        /// Zip multiple files(fileNames) in directory(directory) to (flowName).zip.
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="fileNames"></param>
        /// <param name="reportName"></param>
        public static void PackFilesIntoOne(string directory, string[] fileNames, string outputFilename)
        {
            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }
            if (fileNames == null)
            {
                throw new ArgumentNullException("fileNames");
            }
            if (outputFilename == null)
            {
                throw new ArgumentNullException("outputFilename");
            }
            if (fileNames.Length == 0)
            {
                throw new ArgumentException("Length cannot be 0.", "fileNames");
            }

            string newFilename = Path.Combine(directory, outputFilename);

            if (File.Exists(newFilename))
            {
                File.Delete(newFilename);
            }

            using (FileStream fileStreamOut = File.Create(newFilename))
            {
                using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fileStreamOut))
                {
                    zipOutputStream.SetLevel(9);

                    foreach (string filename in fileNames)
                    {
                        ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(filename);
                        zipOutputStream.PutNextEntry(zipEntry);

                        using (FileStream fileStreamIn = File.OpenRead(Path.Combine(directory, filename)))
                        {
                            const long BUFFER_SIZE  = 8192;
                            long       currentIndex = 0;
                            byte[]     buffer       = new byte[BUFFER_SIZE];
                            if (fileStreamIn.Length <= BUFFER_SIZE)
                            {
                                fileStreamIn.Read(buffer, 0, Convert.ToInt32(fileStreamIn.Length));
                                zipOutputStream.Write(buffer, 0, Convert.ToInt32(fileStreamIn.Length));
                            }
                            else
                            {
                                do
                                {
                                    long remaining = BUFFER_SIZE;
                                    if (currentIndex + BUFFER_SIZE >= fileStreamIn.Length)
                                    {
                                        remaining = fileStreamIn.Length - currentIndex;
                                    }
                                    fileStreamIn.Read(buffer, 0, Convert.ToInt32(remaining));
                                    currentIndex += remaining;

                                    zipOutputStream.Write(buffer, 0, Convert.ToInt32(remaining));
                                } while (currentIndex < fileStreamIn.Length);
                            }
                        } // using ( FileStream fileStreamIn = File.OpenRead( Path.Combine( directory, filename ) ...
                    }     // foreach

                    zipOutputStream.Flush();
                    zipOutputStream.Finish();
                } //using ( ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream( fileStreamOut ) ) ...
            }     // using ( FileStream fileStreamOut = File.Create( newFilename ) ...
        }
        static void HandleZipOutput(FileInfo zipFileInfo, string thumbprint, string pemPublicCert, byte[] cerData, string pemPrivateKey, byte[] pkcs12Data, string password)
        {
            var baseCn = zipFileInfo.Name;
            if (baseCn.EndsWith(".zip"))
            {
                baseCn = baseCn.Substring(0, baseCn.Length - 4);
            }

            using (ZipOutputStream zipOutputStream = new ZipOutputStream(File.Create(zipFileInfo.FullName)))
            {

                //zipOutputStream.SetLevel(9);

                zipOutputStream.UseZip64 = UseZip64.Off; // for OSX to be happy

                if (cerData != null)
                {
                    ZipEntry entry = new ZipEntry(baseCn + "/" + baseCn + "_asBytes.cer");
                    entry.DateTime = DateTime.Now;
                    zipOutputStream.PutNextEntry(entry);

                    byte[] buffer = new byte[4096];
                    using (Stream stream = new MemoryStream(cerData))
                    {
                        int sourceBytes;
                        do
                        {
                            sourceBytes = stream.Read(buffer, 0, buffer.Length);
                            zipOutputStream.Write(buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }
                }

                if (pkcs12Data != null)
                {
                    ZipEntry entry = new ZipEntry(baseCn + "/" + baseCn + ".pfx");
                    entry.DateTime = DateTime.Now;
                    zipOutputStream.PutNextEntry(entry);

                    byte[] buffer = new byte[4096];
                    using (Stream stream = new MemoryStream(pkcs12Data))
                    {
                        int sourceBytes;
                        do
                        {
                            sourceBytes = stream.Read(buffer, 0, buffer.Length);
                            zipOutputStream.Write(buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }
                }

                if (!string.IsNullOrEmpty(pemPrivateKey))
                {
                    MemoryStream ms = new MemoryStream();
                    StreamWriter sw = new StreamWriter(ms);
                    sw.Write(pemPrivateKey);
                    sw.Flush(); //This is required or you get a blank text file :)
                    ms.Position = 0;
                    ZipEntry entry = new ZipEntry(baseCn + "/" + baseCn + ".pem");
                    entry.DateTime = DateTime.Now;
                    zipOutputStream.PutNextEntry(entry);
                    zipOutputStream.Write(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
                }

                if (!string.IsNullOrEmpty(pemPublicCert))
                {
                    MemoryStream ms = new MemoryStream();
                    StreamWriter sw = new StreamWriter(ms);
                    sw.Write(pemPublicCert);
                    sw.Flush(); //This is required or you get a blank text file :)
                    ms.Position = 0;

                    ZipEntry entry = new ZipEntry(baseCn + "/" + baseCn + ".cer");
                    entry.DateTime = DateTime.Now;
                    zipOutputStream.PutNextEntry(entry);
                    zipOutputStream.Write(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
                }

                if (!string.IsNullOrEmpty(thumbprint))
                {
                    MemoryStream ms = new MemoryStream();
                    StreamWriter sw = new StreamWriter(ms);
                    sw.Write(thumbprint);
                    sw.Flush(); //This is required or you get a blank text file :)
                    ms.Position = 0;
                    ZipEntry entry = new ZipEntry(baseCn + "/" + baseCn + "_thumbprint.txt");
                    entry.DateTime = DateTime.Now;
                    zipOutputStream.PutNextEntry(entry);
                    zipOutputStream.Write(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
                }

                if (!string.IsNullOrEmpty(password))
                {
                    MemoryStream ms = new MemoryStream();
                    StreamWriter sw = new StreamWriter(ms);
                    sw.Write(password);
                    sw.Flush(); //This is required or you get a blank text file :)
                    ms.Position = 0;
                    ZipEntry entry = new ZipEntry(baseCn + "/" + baseCn + "_password.txt");
                    entry.DateTime = DateTime.Now;
                    zipOutputStream.PutNextEntry(entry);
                    zipOutputStream.Write(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
                }

                zipOutputStream.Finish();
                zipOutputStream.Flush();
                zipOutputStream.Close();
            }

            Console.WriteLine(string.Format("Certificate files output to '{0}'.", zipFileInfo.FullName));
            Console.WriteLine("---------------------------------------");
            Console.Write(string.Format("Open the directory? (Y + ENTER for yes) > ", zipFileInfo.FullName));
            var resp = Console.ReadLine();
            if (!string.IsNullOrEmpty(resp) && resp.ToLower() == "y")
            {
                string fileToSelect = zipFileInfo.FullName;
                string args = string.Format("/Select, \"{0}\"", fileToSelect);
                Console.WriteLine("Opening directory...");
                ProcessStartInfo pfi = new ProcessStartInfo("Explorer.exe", args);
                System.Diagnostics.Process.Start(pfi);
            }

            Console.WriteLine();
            Console.WriteLine("---------------------------------------");
            Console.WriteLine("Operation complete.");
            Console.WriteLine("---------------------------------------");
            Console.WriteLine();
            Console.WriteLine();
        }
Beispiel #27
0
 /// <summary>
 /// 递归压缩文件夹方法
 /// </summary>
 private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName)
 {
     bool res = true;
     string[] folders, filenames;
     ZipEntry entry = null;
     FileStream fs = null;
     Crc32 crc = new Crc32();
     try
     {
         entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/"));
         s.PutNextEntry(entry);
         s.Flush();
         filenames = Directory.GetFiles(FolderToZip);
         foreach (string file in filenames)
         {
             fs = File.OpenRead(file);
             byte[] buffer = new byte[fs.Length];
             fs.Read(buffer, 0, buffer.Length);
             entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file)));
             entry.DateTime = DateTime.Now;
             entry.Size = fs.Length;
             fs.Close();
             crc.Reset();
             crc.Update(buffer);
             entry.Crc = crc.Value;
             s.PutNextEntry(entry);
             s.Write(buffer, 0, buffer.Length);
         }
     }
     catch
     {
         res = false;
     }
     finally
     {
         if (fs != null)
         {
             fs.Close();
             fs = null;
         }
         if (entry != null)
         {
             entry = null;
         }
         GC.Collect();
         GC.Collect(1);
     }
     folders = Directory.GetDirectories(FolderToZip);
     foreach (string folder in folders)
     {
         if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip))))
         {
             return false;
         }
     }
     return res;
 }
Beispiel #28
0
		public Exception SaveProject(System.IO.Stream myStream)
		{
			Altaxo.Serialization.Xml.XmlStreamSerializationInfo info = new Altaxo.Serialization.Xml.XmlStreamSerializationInfo();
			ZipOutputStream zippedStream = new ZipOutputStream(myStream);
			ZipOutputStreamWrapper zippedStreamWrapper = new ZipOutputStreamWrapper(zippedStream);

			Exception savingException = null;
			try
			{
				this._currentProject.SaveToZippedFile(zippedStreamWrapper, info);

				if (!Current.Gui.InvokeRequired())
					SaveWindowStateToZippedFile(zippedStreamWrapper, info);
			}
			catch (Exception exc)
			{
				savingException = exc;
			}

			zippedStream.Flush();
			zippedStream.Close();
			myStream.Close();
			return savingException;
		}
        /// <summary>
        /// Zips a file
        /// </summary>
        /// <param name="filePath">Path to the source file</param>
        /// <param name="tempOutputFile">temp file to store the zip</param>
        /// <returns>Bool</returns>
        private static bool zipFile(string filePath, string tempOutputFile)
        {
            if (!S3FileExists(filePath)) return false;
            var file = new FileInfo(filePath);

            var parent = Directory.GetParent(tempOutputFile);
            if (!parent.Exists)
                parent.Create();

            using (var fileStreamIn = File.Create(tempOutputFile))
            using (var zipStreamOut = new ZipOutputStream(fileStreamIn))
            {
                // Zip with highest compression.
                zipStreamOut.SetLevel(9);
                var crc = new Crc32();

                using (var fileStream = GetS3File(filePath))
                {

                    // Create a new entry for the current file.
                    var entry = new ZipEntry(file.Name) { DateTime = DateTime.Now };

                    // set Size and the crc, because the information
                    // about the size and crc should be stored in the header
                    // if it is not set it is automatically written in the footer.
                    // (in this case size == crc == -1 in the header)
                    // Some ZIP programs have problems with zip files that don't store
                    // the size and crc in the header.

                    // Reset and update the crc.
                    crc.Reset();

                    zipStreamOut.PutNextEntry(entry);


                    const int maxbufferSize = 1024 * 8;
                    // Read full stream to in-memory buffer, for larger files, only buffer 8 kBytes
                    var buffer = new byte[maxbufferSize];

                    int bytesRead;
                    do
                    {
                        bytesRead = fileStream.Read(buffer, 0, buffer.Length);

                        crc.Update(buffer, 0, bytesRead);
                        zipStreamOut.Write(buffer, 0, bytesRead);

                    } while (bytesRead > 0);

                    // Update entry and write to zip stream.
                    entry.Crc = crc.Value;

                    // Get rid of the buffer, because this
                    // is a huge impact on the memory usage.
                    buffer = null;
                    fileStream.Close();
                }
                // Finalize the zip output.
                zipStreamOut.Finish();


                // Flushes the create and close.
                zipStreamOut.Flush();
                zipStreamOut.Close();
            }
            return true;
        }
    public static void TestBinarySerializationZipped(int len)
    {
      DateTime t1;
      TimeSpan dt;
      double[] arr = new double[len];
      for(int i=0;i<arr.Length;i++)
      {
        arr[i] = Math.PI*Math.Sqrt(i);
      }

      //  FileStream fs = new FileStream(@"C:\TEMP\testbinformat.bin", FileMode.Create);
      System.IO.FileStream zipoutfile = System.IO.File.Create(@"C:\temp\xmltest03.xml.zip");
      ZipOutputStream fs = new ZipOutputStream(zipoutfile);
      ZipEntry ZipEntry = new ZipEntry("Table/Table1.xml");
      fs.PutNextEntry(ZipEntry);
      fs.SetLevel(0);


      // Construct a BinaryFormatter and use it to serialize the data to the stream.
      System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new BinaryFormatter();

      t1 = DateTime.Now;
      try 
      {
        formatter.Serialize(fs, arr);
      }
      catch (SerializationException e) 
      {
        Console.WriteLine("Failed to serialize. Reason: " + e.Message);
        throw;
      }
      finally 
      {
        fs.Flush();
        fs.Close();
      }
      dt = DateTime.Now - t1;
      Console.WriteLine("Duration: {0}",dt);


    }
        public void WriteArchive(HgNodeID changesetNodeID, Stream stream, HgArchiveFormat format, Func<bool> cancellationCallback = null)
        {
            var hgChangeset = hgRepository.Changelog[changesetNodeID];
            var hgManifestEntry = hgRepository.Manifest[hgChangeset.ManifestNodeID];
            
            using(var outputStream = new ZipOutputStream(stream))
            {
                outputStream.SetLevel(3);

                var hgArchival =
                    string.Format(
                        "repo: {0}\nnode: {1}\nbranch: {2}\n",
                        hgRepository.Changelog[0].Metadata.NodeID.Long,
                        changesetNodeID.Long,
                        hgChangeset.Branch.Name);

                var hgTags = hgRepository.GetTags().Where(t => t.Name != "tip" && t.NodeID == changesetNodeID).ToList();
                if(hgTags.Count > 0)
                {
                    hgArchival +=
                        string.Join(
                            "",
                            hgTags.Select(t => string.Format("tag: {0}\n", t.Name)));
                } // if
                else
                {
                    var latestTag = GetLatestTag(hgRepository, changesetNodeID);

                    hgArchival +=
                        string.Format(
                            "latesttag: {0}\nlatesttagdistance: {1}\n",
                            latestTag == null || string.IsNullOrWhiteSpace(latestTag.Item3) ? "null" : latestTag.Item3,
                            latestTag == null ? 0 : latestTag.Item2);
                } // else
                       
                var now = DateTime.UtcNow;
                var buffer = Encoding.ASCII.GetBytes(hgArchival);

                var zipEntry = new ZipEntry(".hg_archival.txt");
                zipEntry.DateTime = now;
                zipEntry.Size = buffer.Length;

                outputStream.PutNextEntry(zipEntry);
                outputStream.Write(buffer, 0, buffer.Length);

                //
                // Now iterate over each file in the manifest
                foreach(var hgManifestFileEntry in hgManifestEntry.Files)
                {
                    if(cancellationCallback != null && cancellationCallback()) return;

                    var hgFile = hgRepository.GetFile(hgManifestFileEntry);

                    zipEntry = new ZipEntry(ZipEntry.CleanName(hgFile.Path.FullPath));
                    zipEntry.DateTime = now;
                    zipEntry.Size = hgFile.Data.Length;

                    outputStream.PutNextEntry(zipEntry);
                    outputStream.Write(hgFile.Data, 0, hgFile.Data.Length);
                } // foreach

                outputStream.Finish();
                outputStream.Flush();
            } // using
        }
Beispiel #32
0
        public static clsResult WriteMemoryToZipEntryAndFlush(MemoryStream Memory, ZipOutputStream Stream)
        {
            clsResult ReturnResult = new clsResult("Writing to zip stream");

            try
            {
                Memory.WriteTo(Stream);
                Memory.Flush();
                Stream.Flush();
                Stream.CloseEntry();
            }
            catch ( Exception ex )
            {
                ReturnResult.ProblemAdd(ex.Message);
                return ReturnResult;
            }

            return ReturnResult;
        }
Beispiel #33
0
        /**
         * Copy all the files in a manifest from input to output.  We set
         * the modification times in the output to a fixed time, so as to
         * reduce variation in the output file and make incremental OTAs
         * more efficient.
         */
        private static void copyFiles(Manifest manifest,
            JarFile in_, ZipOutputStream out_, DateTime timestamp)
        {
            byte[] buffer = new byte[4096];
            int num;

            IDictionary<String, Attributes> entries = manifest.Entries;
            List<String> names = new List<String>(entries.Keys);
            names.Sort();
            foreach (String name in names)
            {
                JarEntry inEntry = in_.GetJarEntry(name);
                JarEntry outEntry = null;
                if (inEntry.CompressionMethod == CompressionMethod.Stored)
                {
                    // Preserve the STORED method of the input entry.
                    outEntry = new JarEntry(inEntry);
                }
                else
                {
                    // Create a new entry so that the compressed len is recomputed.
                    outEntry = new JarEntry(name);
                    if (inEntry.Size > -1)
                        outEntry.Size = inEntry.Size;
                }
                outEntry.DateTime = timestamp;
                out_.PutNextEntry(outEntry);

                Stream data = in_.GetInputStream(inEntry);
                while ((num = data.Read(buffer, 0, buffer.Length)) > 0)
                {
                    out_.Write(buffer, 0, num);
                }
                out_.Flush();
            }
        }
Beispiel #34
0
 /// <summary>
 /// 递归压缩文件夹方法
 /// </summary>
 /// <param name="folderToZip"></param>
 /// <param name="s"></param>
 /// <param name="parentFolderName"></param>
 private bool ZipFileDictory(string folderToZip, ZipOutputStream s, string parentFolderName)
 {
     var res = true;
     ZipEntry entry = null;
     FileStream fs = null;
     var crc = new Crc32();
     try
     {
         //创建当前文件夹
         entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/")); //加上 “/” 才会当成是文件夹创建
         s.PutNextEntry(entry);
         s.Flush();
         //先压缩文件,再递归压缩文件夹
         var filenames = Directory.GetFiles(folderToZip);
         foreach (var file in filenames)
         {
             //打开压缩文件
             fs = File.OpenRead(file);
             var buffer = new byte[fs.Length];
             fs.Read(buffer, 0, buffer.Length);
             entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
             entry.DateTime = DateTime.Now;
             entry.Size = fs.Length;
             fs.Close();
             crc.Reset();
             crc.Update(buffer);
             entry.Crc = crc.Value;
             s.PutNextEntry(entry);
             s.Write(buffer, 0, buffer.Length);
         }
     }
     catch
     {
         res = false;
     }
     finally
     {
         if (fs != null)
         {
             fs.Close();
         }
         if (entry != null)
         {
         }
         GC.Collect();
         GC.Collect(1);
     }
     var folders = Directory.GetDirectories(folderToZip);
     foreach (var folder in folders)
     {
         if (!ZipFileDictory(folder, s, Path.Combine(parentFolderName, Path.GetFileName(folderToZip))))
         {
             return false;
         }
     }
     return res;
 }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        string xType = ddlExportType.SelectedItem.Text;
        bool   xPack = ckbExportMulti.Checked;

        if (xPack)
        {
            Master.Log.Info("Creating package: " + txtZipName.Text);
            if (txtZipName.Text == "")
            {
                lblFNError.Visible = true;
                return;
            }
            else
            {
                lblFNError.Visible = false;
            }

            using (MemoryStream OutputStream = new MemoryStream())
            {
                // Setup Zip Stream
                string zipFileName = txtZipName.Text + ".osapkg";
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(OutputStream);
                zipStream.SetLevel(3);
                zipStream.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.On;
                // Add each object on list to Zip in reverse order.
                int lstCount = lstFileList.Items.Count;
                if (lstCount > 0)
                {
                    //foreach (ListItem lstItem in lstFileList.Items)
                    while (lstCount > 0)
                    {
                        ListItem lstItem = lstFileList.Items[lstCount - 1];
                        int      iSplit  = lstItem.Text.IndexOf("::");
                        string[] args    = new string[2]; //lstItem.Text.Split(':',':');
                        args[0] = lstItem.Text.Substring(0, iSplit);
                        args[1] = lstItem.Text.Substring(iSplit + 2);
                        ExportObject xObj = new ExportObject(args[0], args[1]);
                        Master.Log.Info("Adding file: " + xObj.ExportFileName + " to package: " + txtZipName.Text);
                        ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(xObj.ExportFileName);
                        zipEntry.DateTime = DateTime.Now;
                        zipEntry.Size     = xObj.byteData.Length;
                        zipStream.PutNextEntry(zipEntry);
                        zipStream.Write(xObj.byteData, 0, xObj.byteData.Length);
                        zipStream.Flush();
                        zipStream.CloseEntry();
                        lstCount = lstCount - 1;
                    }
                }

                // Finish up Zip
                zipStream.IsStreamOwner = false;
                zipStream.Close();
                OutputStream.Position = 0;
                byte[] byteArray = OutputStream.GetBuffer();
                Int64  leng      = byteArray.Length;
                Response.Clear();
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + zipFileName);
                Response.AppendHeader("Content-Length", leng.ToString());
                Response.ContentType = "application/zip";
                Response.BinaryWrite(byteArray);
                Response.Flush();
                Master.Log.Info("Exported package: " + txtZipName.Text + " - By User: "******"Username"]);
            }
        }
        else
        {
            // Only 1 File
            lstFileList.Items.Clear();
            ExportObject sExport = new ExportObject(ddlObjToExport.SelectedValue, ddlExportType.SelectedValue);
            Master.Log.Info("Exporting File: " + sExport.ExportFileName + " - By User: "******"Username"]);
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=\"" + sExport.ExportFileName + "\"");
            Response.Charset = "";
            if (sExport.DataType == "Text")
            {
                Response.ContentType = "application/text";
                StringBuilder sb = new StringBuilder(sExport.stringData);
                Response.Output.Write(sb.ToString());
            }
            else if (sExport.Type == "Image")
            {
                Response.ContentType = "image/" + Path.GetExtension(sExport.ExportFileName);
                Response.BinaryWrite(sExport.byteData);
            }
            else
            {
                Response.ContentType = "application/octet-stream";
                Response.AppendHeader("Content-Length", sExport.ByteSize.ToString());
                Response.BinaryWrite(sExport.byteData);
            }
            Response.Flush();
            Response.End();
            //Master.Log.Info("Exported file: " + sExport.ExportFileName + " - By User: "******"Username"]);
        }
        btnClear_Click(this, null);
    }
        }                 // Unpack

        /// <summary>
        /// Zip a file.
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="appendZipExtension"></param>
        public static void PackFile(string filename, bool appendZipExtension)
        {
            if (filename == null)
            {
                throw new ArgumentNullException("filename");
            }
            if (!File.Exists(filename))
            {
                throw new ArgumentException(string.Format("File does not exist: {0}.", filename), "filename");
            }

            string newFilename = filename + ".zip";

            if (!appendZipExtension)
            {
                newFilename = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".zip";
            }
            if (File.Exists(newFilename))
            {
                File.Delete(newFilename);
            }

            FileStream fileStreamOut = File.Create(newFilename);

            ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fileStreamOut);
            zipOutputStream.SetLevel(9);

            ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filename));
            zipOutputStream.PutNextEntry(zipEntry);

            FileStream fileStreamIn = File.OpenRead(filename);
            const long BUFFER_SIZE  = 8192;
            long       currentIndex = 0;

            byte[] buffer = new byte[BUFFER_SIZE];
            if (fileStreamIn.Length <= BUFFER_SIZE)
            {
                fileStreamIn.Read(buffer, 0, Convert.ToInt32(fileStreamIn.Length));
                zipOutputStream.Write(buffer, 0, Convert.ToInt32(fileStreamIn.Length));
            }
            else
            {
                do
                {
                    long remaining = BUFFER_SIZE;
                    if (currentIndex + BUFFER_SIZE >= fileStreamIn.Length)
                    {
                        remaining = fileStreamIn.Length - currentIndex;
                    }
                    fileStreamIn.Read(buffer, 0, Convert.ToInt32(remaining));
                    currentIndex += remaining;

                    zipOutputStream.Write(buffer, 0, Convert.ToInt32(remaining));
                } while (currentIndex < fileStreamIn.Length);
            }
            fileStreamIn.Close();

            zipOutputStream.Flush();
            zipOutputStream.Finish();
            zipOutputStream.Close();

            fileStreamOut.Close();
        }// ZipFile
        /// <summary>
        /// Generates a new error report.
        /// </summary>
        /// <param name="exp">The exp.</param>
        /// <returns></returns>
        /// <remarks>Documented by Dev02, 2009-07-14</remarks>
        private static Stream GenerateReport(Exception exception)
        {
            if (exception == null)
                return null;

            //generate report
            MemoryStream report = new MemoryStream();
            ZipOutputStream zipstream = new ZipOutputStream(report);
            zipstream.UseZip64 = UseZip64.Off;  // AAB-20090720: Zip64 caused some problem when modifing the archive (ErrorReportHandler.cs) - Zip64 is required to bypass the 4.2G limitation of the original Zip format (http://en.wikipedia.org/wiki/ZIP_(file_format))
            zipstream.SetLevel(9);

            AddErrorReport(zipstream, exception);
            AddScreenshot(zipstream);
            AddUserProfileFootPrint(zipstream);
            AddConnections(zipstream);

            zipstream.Finish();
            zipstream.Flush();

            return report;
        }
        public static bool ZipFile(string file, string outPath, string password )
        {
            try
            {
                ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream
                if (password != null && password != String.Empty)
                    oZipStream.Password = password;
                oZipStream.SetLevel(9); // maximum compression
                ZipEntry oZipEntry;
                FileStream ostream;
                byte[] obuffer;

                string f = file;
                Console.WriteLine(" file " + file);
                Console.WriteLine(" file.LastIndexOf('\\'), file.Length-file.LastIndexOf('\\')-1)  rm " + file.Remove(0, file.LastIndexOf('\\') + 1));
                Console.WriteLine(" f " + file);
                if (!file.EndsWith(@"/")) // if a file ends with '/' its a directory
                {
                    oZipEntry = new ZipEntry(file.Remove(0, file.LastIndexOf('\\') + 1));
                    oZipStream.PutNextEntry(oZipEntry);
                    ostream = File.OpenRead(file);
                    obuffer = new byte[ostream.Length];
                    ostream.Read(obuffer, 0, obuffer.Length);
                    oZipStream.Write(obuffer, 0, obuffer.Length);
                    oZipStream.Flush();
                    ostream.Close();
                }

                oZipStream.Finish();
                oZipStream.Close();
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                return false;
            }
        }
Beispiel #39
0
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        static public void CompressByteZip(byte[] inBytes, uint startPos, uint inLen, ref byte[] outBytes, ref uint outLen)
        {
            MemoryStream ms = new MemoryStream();
            ZipOutputStream zipStream = new ZipOutputStream(ms);

            //zipStream.SetLevel(9); // 0 - store only to 9 - means best compression

            ZipEntry entry = new ZipEntry("dummyfile.txt"); // 输出的文件名字
            zipStream.PutNextEntry(entry);

            try
            {
                zipStream.Write(inBytes, 0, (int)inLen);

                zipStream.Flush();
                zipStream.Close();      // 一定要先 Close ZipOutputStream ,然后再获取 ToArray ,如果不关闭, ToArray 将不能返回正确的值

                outBytes = ms.ToArray();
                outLen = (uint)outBytes.Length;
            }
            finally
            {
                zipStream.Close();
                ms.Close();
            }
        }