public void Metro_EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent()
        {
            var data = new byte[] { 1, 2, 3, 4 };

            using (var stream = new MemoryStream())
            {
                using (var zip = new ZipFile())
                {
                    zip.AddEntry(STR_TestBin, data);
                    zip.Save(stream);
                }

                stream.Position = 0;

                using(var zip = ZipFile.Read(stream))
                {
                    using(var ms = new MemoryStream())
                    {
                        zip[STR_TestBin].Extract(ms);

                        var actual = ms.ToArray();

                        CollectionAssert.AreEquivalent(data, actual);
                    }
                }
            }
        }
Beispiel #2
0
	static public void CompressFolder(string aFolderName, string aFullFileOuputName, string[] ExcludedFolderNames, string[] ExcludedFileNames){
		// Perform some simple parameter checking.  More could be done
		// like checking the target file name is ok, disk space, and lots
		// of other things, but for a demo this covers some obvious traps.
		if (!Directory.Exists(aFolderName)) {
			Debug.Log("Cannot find directory : " + aFolderName);
			return;
		}

		try
		{
			string[] exFileNames = new string[0];
			string[] exFolderNames = new string[0];
			if(ExcludedFileNames != null) exFileNames = ExcludedFileNames;
			if(ExcludedFolderNames != null) exFolderNames = ExcludedFolderNames;
			// Depending on the directory this could be very large and would require more attention
			// in a commercial package.
			List<string> filenames = GenerateFolderFileList(aFolderName, null);
			
			//foreach(string filename in filenames) Debug.Log(filename);
			// 'using' statements guarantee the stream is closed properly which is a big source
			// of problems otherwise.  Its exception safe as well which is great.
			using (ZipOutputStream zipOut = new ZipOutputStream(File.Create(aFullFileOuputName))){
			zipOut.Finish();
			zipOut.Close();
			}
			using(ZipFile s = new ZipFile(aFullFileOuputName)){
					s.BeginUpdate();
					int counter = 0;
					//add the file to the zip file
				   	foreach(string filename in filenames){
						bool include = true;
						string entryName = filename.Replace(aFolderName, "");
						//Debug.Log(entryName);
						foreach(string fn in exFolderNames){
							Regex regEx = new Regex(@"^" + fn.Replace(".",@"\."));
							if(regEx.IsMatch(entryName)) include = false;
						}
						foreach(string fn in exFileNames){
							Regex regEx = new Regex(@"^" + fn.Replace(".",@"\."));
							if(regEx.IsMatch(entryName)) include = false;
						}
						if(include){
							s.Add(filename, entryName);
						}
						counter++;
					}
				    //commit the update once we are done
				    s.CommitUpdate();
				    //close the file
				    s.Close();
				}
		}
		catch(Exception ex)
		{
			Debug.Log("Exception during processing" + ex.Message);
			
			// No need to rethrow the exception as for our purposes its handled.
		}
	}
Beispiel #3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt = cm.getdt("SELECT * FROM VW_RFI_ATCH_DTL_ALL_ZIP WHERE RAD_RFH_ID = 97");
        string output = "<style> table { min-width:600px; padding: 0px; box-shadow: 2px 2px 3px #888888; border: 1px solid #cccccc; -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; border-bottom-left-radius: 0px; -moz-border-radius-bottomright: 0px; -webkit-border-bottom-right-radius: 0px; border-bottom-right-radius: 0px; -moz-border-radius-topright: 0px; -webkit-border-top-right-radius: 0px; border-top-right-radius: 0px; -moz-border-radius-topleft: 0px; -webkit-border-top-left-radius: 0px; border-top-left-radius: 0px; } table table { height: 100%; margin: 0px; padding: 0px; } table tr:last-child td:last-child { -moz-border-radius-bottomright: 0px; -webkit-border-bottom-right-radius: 0px; border-bottom-right-radius: 0px; } table table tr:first-child td:first-child { -moz-border-radius-topleft: 0px; -webkit-border-top-left-radius: 0px; border-top-left-radius: 0px; } table table tr:first-child td:last-child { -moz-border-radius-topright: 0px; -webkit-border-top-right-radius: 0px; border-top-right-radius: 0px; } table tr:last-child td:first-child { -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; border-bottom-left-radius: 0px; } table tr:hover td { background-color: #e5e5e5; } table td { vertical-align: middle; background: -o-linear-gradient(bottom, #ffffff 5%, #e5e5e5 100%); background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffffff), color-stop(1, #e5e5e5) ); background: -moz-linear-gradient( center top, #ffffff 5%, #e5e5e5 100% ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e5e5e5'); background: -o-linear-gradient(top,#ffffff,e5e5e5); background-color: #ffffff; border: 1px solid #cccccc; border-width: 0px 1px 1px 0px; text-align: left; padding: 7px 4px 7px 4px; font-size: 10px; font-family: Arial; font-weight: normal; color: #000000; } table tr:last-child td { border-width: 0px 1px 0px 0px; } table tr td:last-child { border-width: 0px 0px 1px 0px; } table tr:last-child td:last-child { border-width: 0px 0px 0px 0px; } table tr:first-child td { background: -o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) ); background: -moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#b2b2b2'); background: -o-linear-gradient(top,#cccccc,b2b2b2); background-color: #cccccc; border: 0px solid #cccccc; text-align: center; border-width: 0px 0px 1px 1px; font-size: 12px; font-family: Arial; font-weight: bold; color: #000000; } table tr:first-child:hover td { background: -o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) ); background: -moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#b2b2b2'); background: -o-linear-gradient(top,#cccccc,b2b2b2); background-color: #cccccc; } table tr:first-child td:first-child { border-width: 0px 0px 1px 0px; } table tr:first-child td:last-child { border-width: 0px 0px 1px 1px; } table th { background: -o-linear-gradient(bottom, #ffffff 5%, #e5e5e5 100%); background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffffff), color-stop(1, #e5e5e5) ); background: -moz-linear-gradient( center top, #ffffff 5%, #e5e5e5 100% ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e5e5e5'); background: -o-linear-gradient(top,#ffffff,e5e5e5); background-color: #ffffff; border: 1px solid #888888; padding: 3px; font-family: Arial; font-size: 12px; } body { font-family: Arial; font-size: 12px; } </style>";
        output += "<div style=''><b>RFI for " + dt.Rows[0]["RAD_RFH_RFINO"].ToString() + "</b></div>";

        using (ZipFile zip = new ZipFile())
        {
            zip.AlternateEncodingUsage = ZipOption.Never;
            output += "<table>";
            output += "<tr><th>RFI Attach Type</th><th>Insepection</th><th>Remark</th><th>Date</th></tr>";
            foreach (DataRow row in dt.Rows)
            {
                output += "<tr>";
                if (File.Exists(Server.MapPath(row["RAD_FILE_SRVR"].ToString())))
                {
                    zip.AddFile(Server.MapPath(row["RAD_FILE_SRVR"].ToString()), (row["file_path"].ToString()));
                    output += "<td>";
                    output += (row["RAD_FILE_SRVR_link"].ToString());
                    output += "</td>";
                    output += "<td>";
                    output += (row["RAD_VAL_TYPE"].ToString());
                    output += "</td>";
                    output += "<td>";
                    output += (row["RAD_REMARKS"].ToString());
                    output += "</td>";
                    output += "<td>";
                    output += (row["RAD_DOC_DT"].ToString());
                    output += "</td>";
                }
                else
                {
                    output += "<td>";
                    output += "No file found";
                    output += "</td>";
                    output += "<td>";
                    output += (row["RAD_VAL_TYPE"].ToString());
                    output += "</td>";
                    output += "<td>";
                    output += (row["RAD_REMARKS"].ToString());
                    output += "</td>";
                    output += "<td>";
                    output += (row["RAD_DOC_DT"].ToString());
                    output += "</td>";
                    //zip.AddFile("");
                }
                output += "</tr>";
            }
            output += "</table>";
            byte[] data = Encoding.UTF8.GetBytes(output);
            zip.AddEntry("info.html", data);
            Response.Clear();
            Response.BufferOutput = false;
            Response.ContentType = "application/zip";
            Response.AddHeader("content-disposition", "attachment; filename=Zip_" + DateTime.Now.ToString("yyyy-MMM-dd-HHmmss") + ".zip");
            zip.Save(Response.OutputStream);
            Response.End();
        }
    }
            protected override void Before_all_tests()
            {
                base.Before_all_tests();

                _xapPath = Path.GetTempFileName() + ".zip";

                _filesToCleanup.Add(_xapPath);

                Action<ZipFile> addTempFileToZip = (zipFile) =>
                {
                    var pathToTempFileToPlaceInXap = Path.GetTempFileName();
                    using (var writer = File.CreateText(pathToTempFileToPlaceInXap))
                    {
                        writer.Close();
                    }
                    zipFile.AddFile(pathToTempFileToPlaceInXap);
                    _filesToCleanup.Add(pathToTempFileToPlaceInXap);
                };

                using (var zipFile = new ZipFile(_xapPath))
                {
                    addTempFileToZip(zipFile);
                    addTempFileToZip(zipFile);
                    addTempFileToZip(zipFile);
                    addTempFileToZip(zipFile);
                    zipFile.Save();
                }

                _testFileCollection = new XapReader(new ConsoleLogger(LogChatterLevels.Full)).LoadXapUnderTest(_xapPath);
            }
        private Action<Stream> GetFileFromZip(string zipPath, string docPath)
        {
            var fileStream = new FileStream(zipPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            var zipFile = new ZipFile(fileStream);
            var zipEntry = zipFile.GetEntry(docPath);

            if (zipEntry == null || zipEntry.IsFile == false)
                return null;

            var data = zipFile.GetInputStream(zipEntry);
            if (data == null) return null;

            return stream =>
                   {
                       try
                       {
                           if (_disableRequestCompression == false)
                               stream = new GZipStream(stream, CompressionMode.Compress, leaveOpen: true);

                           data.CopyTo(stream);
                           stream.Flush();
                       }
                       finally
                       {
                           if (_disableRequestCompression == false)
                               stream.Dispose();
                       }
                   };
        }
	static public void Main(string[] args)
	{
		if ( args.Length < 1 ) {
			Console.WriteLine("Usage: ZipList file");
			return;
		}
		
		if ( !File.Exists(args[0]) ) {
			Console.WriteLine("Cannot find file");
			return;
		}
		
		using (ZipFile zFile = new ZipFile(args[0])) {
			Console.WriteLine("Listing of : " + zFile.Name);
			Console.WriteLine("");
			Console.WriteLine("Raw Size    Size      Date     Time     Name");
			Console.WriteLine("--------  --------  --------  ------  ---------");
			foreach (ZipEntry e in zFile) {
				DateTime d = e.DateTime;
				Console.WriteLine("{0, -10}{1, -10}{2}  {3}   {4}", e.Size, e.CompressedSize,
				                                                    d.ToString("dd-MM-yy"), d.ToString("HH:mm"),
				                                                    e.Name);
			}
		}
	}
        //---------------------------------------------------------------------------------------------------

        //--Загрузка книги-----------------------------------------------------------------------------------
        public ActionResult Download(Int32 id)
        {
            UnPack(id); //--распаковываем книгу--
            string dirZ = dir.Replace("FanFiction", "TempHtml");

            //--Добавляем книгу в .zip архив--
            using (ZipFile zip = new ZipFile())
            {
                zip.TempFileFolder = dir;
                zip.AddFile(dirZ + id.ToString() + ".html","");
                zip.Save(dirZ + id.ToString() + ".zip");
            }

            //--Читаем в поток .zip файл--
            FileStream fin = new FileStream(dirZ + id.ToString() + ".zip", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            StreamReader cin = new StreamReader(fin, System.Text.Encoding.Default);

            string stringStream = cin.ReadToEnd();

            //--Закрываем соединения и удаляем ненужные файлы--
            cin.Close(); fin.Close();
            System.IO.File.Delete(dirZ + id.ToString() + ".zip");
            System.IO.File.Delete(dirZ + id.ToString() + ".html");

            return File(new MemoryStream(System.Text.Encoding.Default.GetBytes(stringStream)), "application/zip", id.ToString() + ".zip");
        }
    public static void Zip(string zipFileName, params string[] files)
    {
        #if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
        string path = Path.GetDirectoryName(zipFileName);
        Directory.CreateDirectory(path);

        using (ZipFile zip = new ZipFile())
        {
            foreach (string file in files)
            {
                zip.AddFile(file, "");
            }
            zip.Save(zipFileName);
        }
        #elif UNITY_ANDROID
        using (AndroidJavaClass zipper = new AndroidJavaClass ("com.tsw.zipper")) {
            {
                zipper.CallStatic ("zip", zipFileName, files);
            }
        }
        #elif UNITY_IPHONE
        foreach (string file in files) {
            addZipFile (file);
        }
        zip (zipFileName);
        #endif
    }
        public void EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent()
        {
            var data = new byte[] { 1, 2, 3, 4 };

            using (var stream = new MemoryStream())
            {
                using (var zip = new ZipFile())
                {
                    zip.AddEntry(STR_TestBin, data);
                    zip.Save(stream);

                    stream.Position = 0;
                    using (var fs = new FileStream(@"C:\Users\Ivan.z\Documents\test.bin.zip", FileMode.OpenOrCreate))
                    {
                        fs.Position = 0;

                        stream.WriteTo(fs);
                    }
                }

                stream.Position = 0;

                using (var zip = ZipFile.Read(stream))
                {
                    using (var ms = new MemoryStream())
                    {
                        zip[STR_TestBin].Extract(ms);

                        var actual = ms.ToArray();

                        CollectionAssert.AreEquivalent(data, actual);
                    }
                }
            }
        }
Beispiel #10
0
    static void ListZipFile(string fileName, string fileFilter, string directoryFilter)
    {
        using (ZipFile zipFile = new ZipFile(fileName)) {
            var localFileFilter = new PathFilter(fileFilter);
            var localDirFilter = new PathFilter(directoryFilter);

            if (zipFile.Count == 0) {
                Console.WriteLine("No entries to list");
            } else {
                for (int i = 0; i < zipFile.Count; ++i) {
                    ZipEntry e = zipFile[i];
                    if (e.IsFile) {
                        string path = Path.GetDirectoryName(e.Name);
                        if (localDirFilter.IsMatch(path)) {
                            if (localFileFilter.IsMatch(Path.GetFileName(e.Name))) {
                                Console.WriteLine(e.Name);
                            }
                        }
                    } else if (e.IsDirectory) {
                        if (localDirFilter.IsMatch(e.Name)) {
                            Console.WriteLine(e.Name);
                        }
                    } else {
                        Console.WriteLine(e.Name);
                    }
                }
            }
        }
    }
Beispiel #11
0
        private void ExportButton_Click(object sender, EventArgs e)
        {
            this.ExportButton.Enabled = false;

            Task.Factory.StartNew(() => {

                var exportPath = Path.Combine(Properties.Settings.Default.RomExportPath,
                _gameData.GameName + ".zip");

                using (var zf = new ZipFile(exportPath))
                {

                    for (int i = 0; i < _gameData.FileNames.Count; i++)
                    {
                        var qr = _dataEngine.Query(_gameData.FileNames[i], _gameData.Crc32s[i]).FirstOrDefault();

                        if (qr != null)
                        {
                            var data = GetZipFileByName(_gameData.FileNames[i], qr.ContainerPath);
                            zf.AddEntry(_gameData.FileNames[i], data);
                        }

                    }
                    zf.Save();
                }

                Invoke(new Action(() => {
                    this.ExportButton.Enabled = true;
                }));
            });
        }
Beispiel #12
0
        /// <summary>
        /// Serialize
        /// </summary>
        /// <param name="site">site</param>
        /// <param name="path">path</param>
        /// <returns></returns>
        public void Serialize(Site site, string path)
        {
            if (site == null)
            {
                throw new ArgumentException("site");
            }
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentException("stream");
            }

            var tempPath = Path.GetTempPath() + "site.xml";
            using (var stream = File.Create(tempPath))
            {
                var serializer = new XmlSerializer(typeof(Site));
                serializer.Serialize(stream, site);
            }

            var packagePath = path + Path.DirectorySeparatorChar + site.Name + ".wbp";
            if (File.Exists(packagePath))
            {
                File.Delete(packagePath);

            }
            using (ZipFile package = new ZipFile(packagePath, Console.Out))
            {
                package.AddFile(tempPath, string.Empty);
                package.AddFiles(site.Resources.Select(r => r.TextData).Where(File.Exists), "resources");
                package.Save();
            }
        }
        private void AddManifest(ZipFile archive)
        {
            byte[] manifestBytes = File.ReadAllBytes(packagePath + @"\source.extension.vsixmanifest");

            manifestBytes = UpdateManifest(manifestBytes);

            archive.AddEntry("extension.vsixmanifest", manifestBytes);
        }
Beispiel #14
0
		/// <include file='Documents/ArchiveManager.xml' path='ArchiveManager/Member[@name="ArchiveManager1"]/*' />                  
		public ArchiveManager(IServiceProvider serviceProvider, string archive)
			: base(serviceProvider) {
			if (archive != null) {
				this.archive = ZipFile.Read(archive);
				archivePath = archive;
				useArchive = true;
			}
		}
Beispiel #15
0
 //здесь создаем архив
 public static void Compress(string directory)
 {
     if (File.Exists(directory + ".zip"))
         File.Delete(directory + ".zip");
     ZipFile zf = new ZipFile(directory + ".zip"); //создаем объект - файл архива
     zf.AddDirectory(directory);    //добавляем туда нашу папку с файлами
     zf.Save();     //сохраняем архив
 }
		private static void SetZipFile(ZipFile zip, ZipFileInfo file)
		{
			if (!string.IsNullOrEmpty(file.Password))
				zip.Password = file.Password;

			zip.Comment = file.Comment;
			zip.CompressionMethod = (Ionic.Zip.CompressionMethod)((int)file.CompressionMethod);
			zip.CompressionLevel = (Ionic.Zlib.CompressionLevel)((int)file.CompressionLevel);
		}
Beispiel #17
0
        public ZipVirtualPathCollection(String virtualPath, VirtualPathType requestType, ZipFile zipFile)
        {
            _paths = new ArrayList();
            _virtualPath = virtualPath;
            _requestType = requestType;
            _zipFile = zipFile;

            PerformEnumeration ();
        }
Beispiel #18
0
        private void FileForm_Load(object sender, EventArgs e)
        {
            this.Icon = Resources.icon;

            if (Clipboard.ContainsFileDropList())
            {

                var fileDropList = Clipboard.GetFileDropList();
                String now = DateTime.Now.ToString("yyyyMMdd_HHmmss");

                if (fileDropList.Count == 1)
                {
                    var path = fileDropList[0];
                    FileAttributes attr = File.GetAttributes(path);

                    if ((attr & FileAttributes.Directory) != FileAttributes.Directory)
                    {
                        var filename = Path.GetFileNameWithoutExtension(path) + "-" + now + Path.GetExtension(path);
                        File.Copy(path, Properties.Settings.Default.savefolder + @"\" + filename);
                        String url = Properties.Settings.Default.urlprefix + filename + Properties.Settings.Default.urlsuffix;

                        richTextBox1.Text += "Added file to Dropbox:\n" + filename;
                        Clipboard.SetDataObject(url, true);

                        return;
                    }
                }

                //Multiple files/directory, zip it
                using (ZipFile zip = new ZipFile())
                {
                    var files = new List<string>();

                    richTextBox1.Text += "Zipped and added multiple files to Dropbox:\n";
                    foreach (var file in fileDropList)
                    {
                        files.Add(file);
                        richTextBox1.Text += file + "\n";
                    }

                    var commonDir = FindCommonDirectoryPath.FindCommonPath("/", files);

                    foreach (var file in files)
                    {
                        zip.AddItem(file, commonDir);
                    }

                    var filename = now + ".zip";
                    zip.Save(Properties.Settings.Default.savefolder + @"\" + filename);
                    String url = Properties.Settings.Default.urlprefix + filename + Properties.Settings.Default.urlsuffix;

                    Clipboard.SetDataObject(url, true);
                    return;
                }

            }
        }
Beispiel #19
0
 public void CreateZip_AddDirectory_BlankName()
 {
     string zipFileToCreate = Path.Combine(TopLevelDir, "CreateZip_AddDirectory_BlankName.zip");
     using (ZipFile zip = new ZipFile(zipFileToCreate))
     {
         zip.AddDirectoryByName("");
         zip.Save();
     }
 }
		/// <summary>
		/// compress a directory
		/// </summary>
		/// <param name="archive"></param>
		/// <param name="directoryName"></param>
		public static void CompressDirectory(ZipFileInfo archive, string directoryName)
		{
			using (var zip = new ZipFile(Encoding.UTF8))
			{
				SetZipFile(zip, archive);
				zip.AddDirectory(directoryName);
				zip.Save(archive.Filename);
			}
		}
Beispiel #21
0
 string GetPartContent(ZipFile zip, string partPath)
 {
     var part = zip[partPath];
     if (part == null)
         return null;
     using (var memoryStream = new MemoryStream()) {
         part.Extract(memoryStream);
         var str =  Encoding.UTF8.GetString(memoryStream.ToArray());
         return str;
     }
 }
Beispiel #22
0
 public static void ZipFolder(string inputFolder, string outputFile, Ionic.Zlib.CompressionLevel level)
 {
     using (ZipFile zip = new ZipFile())
     {
         zip.CompressionLevel = level;
         zip.AddDirectory(inputFolder, "");
         //zip.AddFiles(GenerateFileList(inputFolder));
         //zip.AddDirectory(inputFolder);
         zip.Save(outputFile);
     }
 }
Beispiel #23
0
        public ZipVault(String fileName) 
        {
            using (InternalExpose())
            {
                Zip = new ZipFile(fileName, Encoding.UTF8);
                var zeIndex = Zip.Entries.ToDictionary(ze => ze.FileName, ze => ze);
                Root = new Branch(this, null, null);

                foreach (var value in Zip.Entries.Where(e => !e.IsDirectory && !e.FileName.EndsWith("$")))
                {
                    var contentFile = value.FileName;
                    var metadataFile = contentFile + "$";

                    var valueNode = (Value)Root.CreateValue(value.FileName, ValueKind.RegularAndInternal);
                    valueNode.SetContent(() => zeIndex[contentFile].ExtractEager());
                    valueNode.RawSetMetadata(() => zeIndex.GetOrDefault(metadataFile).ExtractEager());
                }

                foreach (var branch in Zip.Entries.Where(e => e.IsDirectory && !e.FileName.EndsWith("$")))
                {
                    // no need for slash, because dirname includes it
                    var metadataFile = branch.FileName + "$";

                    // some of those branches will already be created by this time
                    var branchNode = (Branch)Root.GetOrCreateBranch(branch.FileName);
                    branchNode.RawSetMetadata(() => zeIndex.GetOrDefault(metadataFile).ExtractEager());
                }

                // for backward compatibility (DO NOT REMOVE again, please)
                var oldVersionStorage = Zip.Entries.SingleOrDefault(e => !e.IsDirectory && 
                    e.FileName == "version$" || e.FileName == "/version$" || e.FileName == "\\version$");
                if (oldVersionStorage != null)
                {
                    var matchingValue = Root.GetValue("version");
                    var possibleOverlap = Root.GetValue("$version");
                    if (matchingValue == null && possibleOverlap == null)
                    {
                        var versionHolder = Root.CreateValue("$version", ValueKind.Regular);
                        versionHolder.SetContent(() => zeIndex[oldVersionStorage.FileName].ExtractEager());
                    }
                }

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

                Root.AfterLoad();
                Root.GetBranchesRecursive().Cast<Branch>().ForEach(b => b.AfterLoad());
                Root.GetValuesRecursive(ValueKind.RegularAndInternal).Cast<Value>().ForEach(v => v.AfterLoad());

                (Id != Guid.Empty).AssertTrue();
                (Revision is UInt64).AssertTrue();
            }
        }
Beispiel #24
0
        public ZipFolder(FileSystem context, ZipFile parent, string path, string filename)
        {
            if (filename.EndsWith("/"))
                filename = filename.Substring(0, filename.Length - 1);

            Name = filename;
            Parent = parent;
            if (path.EndsWith("/"))
                path = path.Substring(0, path.Length - 1);

            this.path = path;
        }
Beispiel #25
0
 private void button1_Click(object sender, EventArgs e)
 {
     OpenFileDialog ofd = new OpenFileDialog();
     FolderBrowserDialog fbd = new FolderBrowserDialog();
     if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         ZipFile zf = new ZipFile("C:\\Users\\cpaine\\Desktop\\MyZipFile.zip");
         zf.AddDirectoryByName("Adam");
         zf.AddFile(ofd.FileName, "Adam");
         //zf.AddDirectory(fbd.SelectedPath, "");
         if.Save;
     }
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        using (var zip = new ZipFile())
        {
            var imagePath = Server.MapPath("~/Images/Sam.jpg");
            zip.AddFile(imagePath);

            zip.AddEntry("ZIPInfo.txt", "This ZIP file was created on " + DateTime.Now);

            var saveToFilePath = Server.MapPath("~/PictureOfSam.zip");
            zip.Save(saveToFilePath);
        }
    }
		/// <summary>
		/// compress any files
		/// </summary>
		/// <param name="archive"></param>
		/// <param name="fileInfos"></param>
		public static void CompressFile(ZipFileInfo archive, List<ZipFileInfo> fileInfos, string directoryPathInArchive)
		{
			using (var zip = new ZipFile(Encoding.UTF8))
			{
				SetZipFile(zip, archive);
				foreach (var file in fileInfos)
				{
					SetZipFile(zip, file);
					zip.AddFile(file.Filename, directoryPathInArchive);
				}
				zip.Save(archive.Filename);
			}
		}
        /// <summary>Packages the data file with its metadata. It also copies the file.</summary>
        /// <param name="dataFilefullPath">The full path of the data file to be packaged.</param>
        /// <returns>FileInfo - The file information of the packaged data file.</returns>
        /// \author  Ammar Alrashed
        /// \date    07/24/2012
        public static FileInfo PackageDataFile(string dataFilefullPath)
        {
            string dataFileName = Path.GetFileName(dataFilefullPath);

            // Create the directory defined above to package the file inside it.
            DirectoryInfo packagingDirectoryInfo = CreatePackagingFolder(dataFileName);

            FileInfo packagedFileInfo = null;
            try
            {
                // Copy the file to be package to the folder where we'll package it.
                string copiedFileFullPath = Path.Combine(packagingDirectoryInfo.FullName, dataFileName);
                File.Copy(dataFilefullPath, copiedFileFullPath);

                // Create the metadata file inside this folder.
                CreateMetadataFile(dataFileName, packagingDirectoryInfo.FullName);

                // Compress the complete directory.
                string packagedFilePath = Path.Combine(packagingDirectoryInfo.FullName, temporaryZipName);
                Logger.LogDebug(logTag, "Packaging files in " + packagedFilePath);
                using (ZipFile zip = new ZipFile())
                {
                    zip.AddDirectory(packagingDirectoryInfo.FullName);
                    zip.ParallelDeflateThreshold = -1;
                    zip.Save(packagedFilePath);
                }

                // We want to calculate the file's hash, and rename it to that same hash to identify it.
                string fileHash = string.Empty;
                using (FileStream openFileStream = File.Open(packagedFilePath, FileMode.Open))
                {
                    fileHash = HashCalculator.CalculateHashOfFile(openFileStream);
                }

                // The final packaged file with the hash as its name will be moved to the base packaging directory.
                string agentRootDirectory = AppDomain.CurrentDomain.BaseDirectory;
                string finalPackagedFilePath = Path.Combine(agentRootDirectory, temporaryPackagingFolderName, fileHash);
                File.Move(packagedFilePath, finalPackagedFilePath);
                packagedFileInfo = new FileInfo(finalPackagedFilePath);
                Logger.LogDebug(logTag, "Packaged file copied and renamed to " + packagedFileInfo.FullName);
            }
            finally
            {
                // Delete the temporary folder we used to put all the files to compress.
                bool recursiveDelete = true;
                Directory.Delete(packagingDirectoryInfo.FullName, recursiveDelete);
            }

            // Return the information of the newly created, packaged file.
            return packagedFileInfo;
        }
Beispiel #29
0
    static void BuildRelease(BuildTarget target)
    {
        BuildSettings buildSettings = Resources.Load("Build Settings", typeof(BuildSettings)) as BuildSettings;

        if(buildSettings == null)
        {
            Debug.LogError("Can't find build settings");
            return;
        }

        string targetString = "";
        string releaseName = "";

        switch (target)
        {
            case BuildTarget.StandaloneOSXIntel64:
                releaseName = buildSettings.osx_exe;
                targetString = "Mac";
                break;
            case BuildTarget.StandaloneLinux64:
                releaseName = buildSettings.linux_exe;
                targetString = "Linux";
                break;
            case BuildTarget.StandaloneWindows:
                releaseName = buildSettings.win_exe;
                targetString = "Win";
                break;
            case BuildTarget.StandaloneWindows64:
                releaseName = buildSettings.win_exe;
                targetString = "Win x64";
                break;
            default:
                break;
        }

        string path = "Build/" + buildSettings.content_version + "/" + targetString + "/";

        if (Directory.Exists(path))
            Directory.Delete(path, true);

        string[] levels = new string[] { "Assets/Start.unity" };
        EditorUserBuildSettings.SetPlatformSettings("Standalone", "CopyPDBFiles", "false");
        Debug.Log(BuildPipeline.BuildPlayer(levels, path + releaseName, target, BuildOptions.None));
        CopyExtras(path);

        using (ZipFile zip = new ZipFile())
        {
            zip.AddDirectory(path);
            zip.Save("Build/" + buildSettings.title + " " + buildSettings.content_version + " " + targetString + ".zip");
        }
    }
Beispiel #30
0
        public static void ExtractZipFileToDirectory(string archiveFilenameIn, string password, string outFolder)
        {
            ZipFile zf = null;
            try
            {
                var fs = File.OpenRead(archiveFilenameIn);
                zf = new ZipFile(fs);
                if (!String.IsNullOrEmpty(password))
                {
                    zf.Password = password;     // AES encrypted entries are handled automatically
                }

                foreach (ZipEntry zipEntry in zf)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue;           // Ignore directories
                    }
                    var entryFileName = zipEntry.Name;
                    // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                    // Optionally match entrynames against a selection list here to skip as desired.
                    // The unpacked length is available in the zipEntry.Size property.

                    var buffer = new byte[4096];     // 4K is optimum
                    var zipStream = zf.GetInputStream(zipEntry);

                    // Manipulate the output filename here as desired.
                    var fullZipToPath = Path.Combine(outFolder, entryFileName);
                    var directoryName = Path.GetDirectoryName(fullZipToPath);
                    if (!string.IsNullOrEmpty(directoryName))
                        Directory.CreateDirectory(directoryName);

                    // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                    // of the file, but does not waste memory.
                    // The "using" will close the stream even if an exception occurs.
                    using (var streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close(); // Ensure we release resources
                }
            }
        }
Beispiel #31
0
        public static void ExtractArchive([NotNull] string archivePath, [NotNull] string destination,
                                          [NotNull] string infoFilename = ArchiveInfoFile)
        {
            if (string.IsNullOrWhiteSpace(archivePath))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(archivePath));
            }
            if (string.IsNullOrWhiteSpace(destination))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(destination));
            }
            if (string.IsNullOrWhiteSpace(infoFilename))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(infoFilename));
            }
            if (Directory.Exists(destination))
            {
                throw new IOException($"{destination} already exists");
            }

            List <string>    files        = new();
            HashSet <string> directories  = new();
            string           infoFilePath = Path.Combine(destination, infoFilename);

            try
            {
                using ZipArchive zip = ZipFile.OpenRead(archivePath);

                foreach (ZipArchiveEntry entry in zip.Entries)
                {
                    string destinationPath = Path.Combine(destination, entry.FullName);
                    string destinationDir  = Path.GetDirectoryName(destinationPath);
                    if (!string.IsNullOrEmpty(destinationDir) && !Directory.Exists(destinationDir))
                    {
                        Directory.CreateDirectory(destinationDir);
                    }
                    entry.ExtractToFile(destinationPath);

                    // store relative paths
                    if (!string.IsNullOrEmpty(entry.FullName))
                    {
                        files.Add(entry.FullName);
                    }
                    string entryDir = Path.GetDirectoryName(entry.FullName);
                    if (!string.IsNullOrEmpty(entryDir))
                    {
                        directories.Add(entryDir);
                    }
                }

                // use reversed directories to put child directories higher, seems to work at least for burst package
                files.AddRange(directories.Reverse());
                WriteFileList(infoFilePath, files);
            }
            catch
            {
                // remove extracted files
                if (File.Exists(infoFilePath))
                {
                    File.Delete(infoFilePath);
                }
                RemoveFiles(destination, files);
                RemoveFiles(destination, directories.Reverse());

                throw;
            }
        }
        /// <summary>
        /// Deserializes the portal.
        /// </summary>
        /// <param name="file">
        /// The file.
        /// </param>
        /// <param name="portalName">
        /// Name of the portal.
        /// </param>
        /// <param name="portalAlias">
        /// The portal alias.
        /// </param>
        /// <param name="portalPath">
        /// The portal path.
        /// </param>
        /// <param name="portalId">
        /// The portal id.
        /// </param>
        /// <returns>
        /// The deserialize portal.
        /// </returns>
        public bool DeserializePortal(
            string file, string portalName, string portalAlias, string portalPath, string filePath, out int portalId)
        {
            var result = true;

            try {
                PortalsDTO portal;
                if (file.EndsWith("AppleSeedTemplates"))
                {
                    using (var ms = new MemoryStream()) {
                        using (ZipFile zip = ZipFile.Read(GetPhysicalPackageTemplatesPath(filePath) + "\\" + file)) {
                            if (zip.Count == 1)
                            {
                                ms.Position = 0;
                                string   name = file.Replace(".AppleSeedTemplates", ".XML");
                                ZipEntry e    = zip[name];
                                e.Extract(ms);

                                //FileStream s = new FileStream(GetPhysicalPackageTemplatesPath("") + "\\" + name, FileMode.Create);
                                //int pos = int.Parse(ms.Position.ToString());
                                //s.Write(ms.GetBuffer(), 0, pos);
                                //s.Close();

                                ms.Position = 0;

                                var xs = new XmlSerializer(typeof(PortalsDTO));
                                portal = (PortalsDTO)xs.Deserialize(ms);

                                ms.Close();
                            }
                            else
                            {
                                portal = null;
                            }
                        }
                        // the application can now access the MemoryStream here
                    }
                }
                else
                {
                    var fs = new FileStream(GetPhysicalPackageTemplatesPath(filePath) + "\\" + file, FileMode.Open);
                    var xs = new XmlSerializer(typeof(PortalsDTO));
                    portal = (PortalsDTO)xs.Deserialize(fs);
                    fs.Close();
                }

                var db             = new PortalTemplateDataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                var desktopSources = this.iptRepository.GetDesktopSources();

                var translate = new Translate {
                    DesktopSources = desktopSources, PTDataContext = db
                };
                var _portal = translate.TranslatePortalDTOIntoRb_Portals(portal);
                this.ModulesNotInserted = translate.ModulesNotInserted;

                _portal.PortalName  = portalName;
                _portal.PortalPath  = portalPath;
                _portal.PortalAlias = portalAlias;

                db.rb_Portals.InsertOnSubmit(_portal);

                db.SubmitChanges(ConflictMode.FailOnFirstConflict);
                portalId = _portal.PortalID;
                this.SaveModuleContent(_portal, desktopSources, translate.ContentModules);
                AlterModuleSettings(_portal, translate.PageList, desktopSources);
                AlterModuleDefinitions(_portal.PortalID, translate.ModuleDefinitionsDeserialized);
            } catch (Exception ex) {
                result   = false;
                portalId = -1;
                ErrorHandler.Publish(LogLevel.Error, "There was an error on creating the portal", ex);
            }

            return(result);
        }
Beispiel #33
0
        private void DeployCdw800()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            if (!string.IsNullOrEmpty(ProductAppDataPath))
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();

                string markerFile   = Path.Combine(ProductAppDataPath, "ChemDoodle-Web-800.txt");
                string otherVersion = Path.Combine(ProductAppDataPath, "ChemDoodle-Web-702.txt");
                string refreshFile  = Path.Combine(ProductAppDataPath, "ChemDoodle-Web-Refresh.txt");

                if (File.Exists(otherVersion))
                {
                    Telemetry.Write(module, "Information", "Deleting CDW 702 resources from disk");

                    File.Delete(otherVersion);

                    DelTree(Path.Combine(ProductAppDataPath, "ChemDoodleWeb"));
                }

                if (File.Exists(refreshFile))
                {
                    Telemetry.Write(module, "Information", "Refreshing CDW 800 resources");

                    File.Delete(refreshFile);
                    if (File.Exists(markerFile))
                    {
                        File.Delete(markerFile);
                    }

                    DelTree(Path.Combine(ProductAppDataPath, "ChemDoodleWeb"));
                }

                if (!File.Exists(markerFile))
                {
                    Telemetry.Write(module, "Information", "Writing CDW 800 resources to disk");

                    File.WriteAllText(markerFile, "Delete this file to refresh ChemDoodle Web");

                    Stream stream = ResourceHelper.GetBinaryResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.ChemDoodleWeb_800.zip");

                    // NB: Top level of zip file must be the folder ChemDoodleWeb
                    using (ZipFile zip = ZipFile.Read(stream))
                    {
                        zip.ExtractAll(ProductAppDataPath, ExtractExistingFileAction.OverwriteSilently);
                    }

                    string cssfile = ResourceHelper.GetStringResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.Chem4Word.css");
                    File.WriteAllText(Path.Combine(ProductAppDataPath, "Chem4Word.css"), cssfile);

                    string jsfile = ResourceHelper.GetStringResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.Chem4Word.js");
                    File.WriteAllText(Path.Combine(ProductAppDataPath, "Chem4Word.js"), jsfile);
                }

                sw.Stop();

                Telemetry.Write(module, "Timing", $"Writing resources to disk took {SafeDouble.Duration(sw.ElapsedMilliseconds)}ms");
            }
        }
Beispiel #34
0
        public void DownloadMods(string[] verifiedMods, string[] communityMods)
        {
            int    s  = 0;
            int    f  = 0;
            string sp = "";
            string fp = "";

            // attempt to download all verified plugins
            if (verifiedMods.Length > 0)
            {
                for (int i = 0; i < verifiedMods.Length; i++)
                {
                    try
                    {
                        string beatModsOutput = new WebClient().DownloadString($"https://beatmods.com/api/v1/mod?status=approved&name={verifiedMods[i]}&gameVersion={gameVersion}");
                        beatModsOutput = beatModsOutput.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
                        JObject  beatModsJson = JObject.Parse(beatModsOutput);
                        string   downloadLink = $"https://beatmods.com{beatModsJson.SelectToken("$.downloads[0].url")}";
                        string[] fileNameArgs = beatModsJson.SelectToken("$.downloads[0].url").ToString().Split('/');
                        String   fileName     = fileNameArgs[fileNameArgs.Length - 1];
                        Log.Info($"Attempting to download {verifiedMods[i]} from {downloadLink}");
                        new WebClient().DownloadFile(downloadLink, Path.Combine(UnityGame.InstallPath, fileName));
                        string zipFileLocation = Path.Combine(UnityGame.InstallPath, fileName);
                        ZipFile.ExtractToDirectory(zipFileLocation, UnityGame.InstallPath);
                        File.Delete(zipFileLocation);
                        s++;
                    } catch (Exception e)
                    {
                        Log.Log(IPALogger.Level.Info, $"Failed to download verified plugin: {e}");
                        f++;
                    }
                }
            }

            // attempt to download all github plugins
            if (communityMods.Length > 0)
            {
                for (int i = 0; i < communityMods.Length; i++)
                {
                    string[] urlArgs = communityMods[i].Split('.');
                    try
                    {
                        new WebClient().DownloadFile($"https://github.com/{urlArgs[0]}/{urlArgs[1]}/releases/latest/download/{urlArgs[2]}.dll", Path.Combine(IPA.Utilities.UnityGame.InstallPath, "Plugins", $"{urlArgs[2]}.dll"));
                        s++;
                    }
                    catch (System.Exception e)
                    {
                        Log.Log(IPALogger.Level.Info, $"Failed to download custom plugin: {e}");
                        f++;
                    }
                }
            }

            // installsucceeded or installfailed screen
            if (s != 1)
            {
                sp = "s";
            }
            if (f != 1)
            {
                fp = "s";
            }
            Log.Info($"{s} mod{sp} successfully installed, {f} mod{fp} failed to install.");
            controller.ToggleMenuVisible("spn", false);
            controller.ToggleMenuVisible("mpn", false);
            if (s > 0)
            {
                controller.ToggleMenuVisible("is", true);
                controller.isText.text = $"{s} mod{sp} successfully installed, {f} mod{fp} failed to install.";
            }
            else
            {
                controller.ToggleMenuVisible("if", true);
                controller.ifText.text = $"Mod{fp} failed to install.";
            }
        }
Beispiel #35
0
 /// <summary>
 /// Installs library.
 /// </summary>
 /// <param name="checkForPackageHash"><code>True</code> to check for package (zip) hash.</param>
 /// <param name="checkForExistanceAfterInstall"><code>True</code> to additionally validate existance of vlc library after deployment.</param>
 /// <param name="checkExtractedHashes"><code>True</code> to check deployed file hashes.</param>
 /// <param name="tryLoad"><code>True</code> to try loading library.</param>
 public void Install(bool checkForPackageHash, bool checkForExistanceAfterInstall, bool checkExtractedHashes, bool tryLoad)
 {
     if (!File.Exists(packageLocation))
     {
         throw new FileNotFoundException("Package file not found.", packageLocation);
     }
     if (!Directory.Exists(deploymentLocation))
     {
         Directory.CreateDirectory(deploymentLocation);
     }
     if (checkForPackageHash)
     {
         using (Stream stream = File.Open(packageLocation, FileMode.Open, FileAccess.Read, FileShare.None)) {
             byte[] hash       = hashReceiver.ComputeHash(stream);
             string hashBase64 = Convert.ToBase64String(hash);
             //
             if (string.Compare(packageHash, hashBase64) != 0)
             {
                 throw new VlcDeploymentException("Package hash differs from original.");
             }
             //
             stream.Position = 0;
             stream.Close();
         }
     }
     //
     try {
         byte[] buffer = new byte[1024];
         using (ZipFile file = new ZipFile(packageLocation)) {
             foreach (ZipEntry entry in file)
             {
                 //
                 if (entry.IsDirectory)
                 {
                     string dir = Path.Combine(deploymentLocation, entry.Name);
                     if (!Directory.Exists(dir))
                     {
                         Directory.CreateDirectory(dir);
                     }
                 }
                 else if (entry.IsFile)
                 {
                     string fileName = Path.GetFileName(entry.Name);
                     string dir      = Path.Combine(deploymentLocation, Path.GetDirectoryName(entry.Name));
                     //
                     if (!Directory.Exists(dir))
                     {
                         Directory.CreateDirectory(dir);
                     }
                     string filePath = Path.Combine(dir, fileName);
                     if (File.Exists(filePath))
                     {
                         File.Delete(filePath);
                     }
                     using (FileStream stream = File.Create(filePath)) {
                         StreamUtils.Copy(file.GetInputStream(entry), stream, buffer);
                     }
                 }
                 //
             }
         }
     } catch (Exception exc) {
         throw new VlcDeploymentException("Cannot open package or/and extract package.", exc);
     }
     //
     if (checkForExistanceAfterInstall)
     {
         if (!CheckVlcLibraryExistence(checkExtractedHashes, tryLoad))
         {
             throw new VlcDeploymentException("Library cannot be loaded after install. Fatal error. See fail reason.");
         }
     }
 }
Beispiel #36
0
        protected async Task <Response> Process(string controllerName, string fileName, string folderName, string outFileExtension, bool createZip, ActionDelegate action)
        {
            string logMsg = "ControllerName: " + controllerName + " FileName: " + fileName + " OutFileExtension: " + outFileExtension;
            var    watch  = System.Diagnostics.Stopwatch.StartNew();

            string guid         = folderName;
            string sourceFolder = AppSettings.WorkingDirectory + folderName;

            fileName = sourceFolder + "/" + fileName;

            string outfileName = Path.GetFileNameWithoutExtension(fileName) + outFileExtension;
            string outPath     = AppSettings.OutputDirectory + "/" + guid;

            string zipOutfileName = Path.GetFileNameWithoutExtension(fileName) + ".zip";
            string zipOutPath     = AppSettings.OutputDirectory + zipOutfileName;
            string zipOutFolder   = AppSettings.OutputDirectory + guid;

            string    statusValue     = "OK";
            int       statusCodeValue = 200;
            Exception ex = null;

            try
            {
                if (System.IO.File.Exists(zipOutPath))
                {
                    System.IO.File.Delete(zipOutPath);
                }
                if (!createZip)
                {
                    if (!Directory.Exists(outPath))
                    {
                        Directory.CreateDirectory(outPath);
                    }
                }
                outPath += "/" + outfileName;
                action(fileName, outPath, zipOutFolder);

                if (Directory.GetFiles(AppSettings.OutputDirectory + "/" + guid + "/").Length > 1)
                {
                    createZip = true;
                }
                else
                {
                    createZip = false;
                }

                if (createZip)
                {
                    outfileName = Path.GetFileNameWithoutExtension(fileName) + outFileExtension;
                    outPath     = zipOutFolder + "/" + outfileName;
                    Directory.CreateDirectory(zipOutFolder);
                }

                if (createZip)
                {
                    ZipFile.CreateFromDirectory(zipOutFolder, zipOutPath);
                    Directory.Delete(zipOutFolder, true);
                    outfileName = zipOutfileName;
                }

                try
                {
                    //Directory.Delete(sourceFolder, true);
                }
                catch
                { }
            }
            catch (Exception exc)
            {
                string statusMessage = "500 " + exc.Message;
                statusValue = exc.Message;
                if (exc.Message.Contains("The given key was not present in the dictionary"))
                {
                    statusValue = "Conversion from '" + Path.GetExtension(fileName).ToUpper() + "' to '" + outFileExtension.ToUpper() + "' is not supported.";
                }
                statusCodeValue = 500;
                ex = exc;
            }

            return(await Task.FromResult(new Response
            {
                FileName = (createZip ? outfileName : folderName + "/" + outfileName),
                Status = statusValue,
                StatusCode = statusCodeValue,
                exc = ex
            }));
        }
Beispiel #37
0
 protected override Task <ZipArchive> GetZipArchive(string filePath)
 {
     return(Task.FromResult(ZipFile.Open(filePath, ZipArchiveMode.Read, System.Text.Encoding.UTF8)));
 }
Beispiel #38
0
 /// <summary>Opens a zip archive at the specified path and in the specified mode.</summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="mode">
 ///     One of the enumeration values that specifies the actions that are allowed
 ///     on the entries in the opened archive.
 /// </param>
 /// <returns>A ZipArchive.</returns>
 public static ZipArchive OpenZipFile(this FileInfo @this, ZipArchiveMode mode)
 {
     return(ZipFile.Open(@this.FullName, mode));
 }
Beispiel #39
0
 /// <summary>Opens a zip archive at the specified path and in the specified mode.</summary>
 /// <param name="this">
 ///     The path to the archive to open, specified as a relative or absolute
 ///     path. A relative path is interpreted as relative to the current working directory.
 /// </param>
 /// <param name="mode">
 ///     One of the enumeration values that specifies the actions that are allowed
 ///     on the entries in the opened archive.
 /// </param>
 /// <param name="entryNameEncoding">
 ///     The encoding to use when reading or writing entry names in
 ///     this archive. Specify a value for this parameter only when an encoding is required for
 ///     interoperability with zip archive tools and libraries that do not support UTF-8 encoding for
 ///     entry names.
 /// </param>
 /// <returns>A ZipArchive.</returns>
 public static ZipArchive OpenZipFile(this FileInfo @this, ZipArchiveMode mode, Encoding entryNameEncoding)
 {
     return(ZipFile.Open(@this.FullName, mode, entryNameEncoding));
 }
Beispiel #40
0
        private static void UnzipFileToDirectory(string filePath, string unZipDirecotyPath, Action <float> progressAction, Action doneAction, Action errorAction)
        {
            ZipInputStream zipStream = null;
            FileStream     stream    = null;
            ZipFile        zipFile   = null;

            try
            {
                zipFile = new ZipFile(filePath);
                var entryCountDelta = 1f / zipFile.Count;
                zipFile.Close();
                zipFile = null;

                var currentEntryCount = 0;
                var currentProgress   = 0f;

                zipStream = new ZipInputStream(File.OpenRead(filePath));
                ZipEntry zipEntry = null;

                if ((zipEntry = zipStream.GetNextEntry()) != null)
                {
                    var buffer = new byte[4096];
                    while (zipEntry != null && GameRuntimeInfo.IsRunning)
                    {
                        string fileName = Path.GetFileName(zipEntry.Name);
                        if (!string.IsNullOrEmpty(fileName))
                        {
                            if (zipEntry.CompressedSize != 0)
                            {
                                var path    = Path.Combine(unZipDirecotyPath, zipEntry.Name);
                                var dirPath = Path.GetDirectoryName(path);
                                if (!Directory.Exists(dirPath))
                                {
                                    Directory.CreateDirectory(dirPath);
                                }

                                var fileSizeBase = 1f / zipEntry.Size;
                                var processSize  = 0;
                                stream = File.Create(path);
                                while (GameRuntimeInfo.IsRunning)
                                {
                                    int size = zipStream.Read(buffer, 0, buffer.Length);
                                    if (size > 0)
                                    {
                                        stream.Write(buffer, 0, size);
                                        processSize += size;
                                        progressAction((currentProgress + Mathf.Max(fileSizeBase * processSize * entryCountDelta, 0)) * 100);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                stream.Flush();
                                stream.Close();
                                stream = null;
                            }
                        }

                        ++currentEntryCount;
                        currentProgress = currentEntryCount * entryCountDelta;
                        //progressAction(currentProgress * 100);
                        zipEntry = zipStream.GetNextEntry();
                    }
                }
                doneAction();
            }
            catch (Exception e)
            {
                Debug.LogError("unzip file to directory error:" + e);
                errorAction();
            }
            finally
            {
                if (stream != null)
                {
                    stream.Flush();
                    stream.Close();
                }

                if (zipStream != null)
                {
                    zipStream.Flush();
                    zipStream.Close();
                }

                if (zipFile != null)
                {
                    zipFile.Close();
                }
            }
        }
Beispiel #41
0
 /// <summary>
 ///     Creates a zip archive that contains the files and directories from the specified
 ///     directory, uses the specified compression level, and optionally includes the base directory.
 /// </summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="destinationArchiveFile">
 ///     The path of the archive to be created, specified as a
 ///     relative or absolute path. A relative path is interpreted as relative to the current working
 ///     directory.
 /// </param>
 /// <param name="compressionLevel">
 ///     One of the enumeration values that indicates whether to
 ///     emphasize speed or compression effectiveness when creating the entry.
 /// </param>
 /// <param name="includeBaseDirectory">
 ///     true to include the directory name from
 ///     sourceDirectoryName at the root of the archive; false to include only the contents of the
 ///     directory.
 /// </param>
 public static void CreateZipFile(this DirectoryInfo @this, FileInfo destinationArchiveFile, CompressionLevel compressionLevel, bool includeBaseDirectory)
 {
     ZipFile.CreateFromDirectory(@this.FullName, destinationArchiveFile.FullName, compressionLevel, includeBaseDirectory);
 }
Beispiel #42
0
        private async void Compress()
        {
            try
            {
                string zipFileName = Guid.ToString().Replace("-", "") + "_" + DateTime.UtcNow.ToString("yyyyMMddhhmmss") + "_Data_zip";
                string zipFolder   = Path.Combine(TelemetryFolder, "Zip");

                if (!Directory.Exists(zipFolder))
                {
                    Directory.CreateDirectory(zipFolder);
                }

                string LocalZipfileName = Path.Combine(zipFolder, zipFileName);

                ZipFile.CreateFromDirectory(TelemetryDataFolder, LocalZipfileName);

                if (File.Exists(LocalZipfileName))
                {
                    foreach (string fn in Directory.GetFiles(TelemetryDataFolder))
                    {
                        File.Delete(fn);
                    }
                }

                if (!NetworkAvailable)
                {
                    return;
                }


                // TODO; run in parallel
                foreach (string zipfile in Directory.GetFiles(zipFolder))
                {
                    FileStream    fileStream = new FileStream(Path.Combine(TelemetryFolder, zipfile), FileMode.Open);
                    StreamContent content    = new StreamContent(fileStream);
                    try
                    {
                        HttpResponseMessage response = await mClient.PostAsync("api/Telemetry/" + zipFileName.Replace(".", "_"), content);

                        string rc = await response.Content.ReadAsStringAsync();

                        fileStream.Close();

                        if (response.IsSuccessStatusCode)
                        {
                            if (rc == "OK")
                            {
                                System.IO.File.Delete(zipfile);
                            }
                        }
                        else
                        {
                            //
                        }
                    }
                    catch
                    {
                        // Failed to upload
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Telemetry Ex: " + ex.Message);
            }

            done = true;
        }
Beispiel #43
0
 /// <summary>
 ///     Creates a DEFLATE archive for the provided source Directory at the given target.
 /// </summary>
 /// <param name="target">
 ///     Target archive which will contain the compressed source Directory.
 /// </param>
 /// <param name="source">
 ///     Source Directory on the filesystem to compress to the target archive.
 /// </param>
 public void Compress(File target, Directory source)
 {
     ZipFile.CreateFromDirectory(source, target, Level, true);
 }
Beispiel #44
0
        protected override void Execute(GVFSEnlistment enlistment)
        {
            string diagnosticsRoot = Path.Combine(enlistment.DotGVFSRoot, "diagnostics");

            if (!Directory.Exists(diagnosticsRoot))
            {
                Directory.CreateDirectory(diagnosticsRoot);
            }

            string archiveFolderPath = Path.Combine(diagnosticsRoot, "gvfs_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"));

            Directory.CreateDirectory(archiveFolderPath);

            using (FileStream diagnosticLogFile = new FileStream(Path.Combine(archiveFolderPath, "diagnostics.log"), FileMode.CreateNew))
                using (this.diagnosticLogFileWriter = new StreamWriter(diagnosticLogFile))
                {
                    this.WriteMessage("Collecting diagnostic info into temp folder " + archiveFolderPath);

                    this.WriteMessage(string.Empty);
                    this.WriteMessage("gvfs version " + ProcessHelper.GetCurrentProcessVersion());
                    this.WriteMessage(GitProcess.Version(enlistment).Output);
                    this.WriteMessage(GitProcess.GetInstalledGitBinPath());
                    this.WriteMessage(string.Empty);
                    this.WriteMessage("Enlistment root: " + enlistment.EnlistmentRoot);
                    this.WriteMessage("Repo URL: " + enlistment.RepoUrl);
                    this.WriteMessage("Objects URL: " + enlistment.ObjectsEndpointUrl);
                    this.WriteMessage(string.Empty);

                    this.WriteMessage("Copying .gvfs folder...");
                    this.CopyAllFiles(enlistment.EnlistmentRoot, archiveFolderPath, GVFSConstants.DotGVFS.Root, copySubFolders: false);

                    this.WriteMessage("Copying GVFlt logs...");
                    this.FlushGvFltLogBuffers();
                    string system32LogFilesPath = Environment.ExpandEnvironmentVariables(System32LogFilesRoot);
                    this.CopyAllFiles(system32LogFilesPath, archiveFolderPath, GVFltLogFolderName, copySubFolders: false);

                    this.WriteMessage("Checking on GVFS...");
                    this.RunAndRecordGVFSVerb <LogVerb>(archiveFolderPath, "gvfs_log.txt");
                    ReturnCode statusResult = this.RunAndRecordGVFSVerb <StatusVerb>(archiveFolderPath, "gvfs_status.txt");

                    if (statusResult == ReturnCode.Success)
                    {
                        this.WriteMessage("GVFS is mounted. Unmounting so we can read files that GVFS has locked...");
                        this.RunAndRecordGVFSVerb <UnmountVerb>(archiveFolderPath, "gvfs_unmount.txt");
                    }
                    else
                    {
                        this.WriteMessage("GVFS was not mounted.");
                    }

                    this.WriteMessage("Checking Defender exclusion...");
                    this.WriteAntiVirusExclusions(enlistment.EnlistmentRoot, archiveFolderPath, "DefenderExclusionInfo.txt");

                    this.WriteMessage("Copying .git folder...");
                    this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Root, copySubFolders: false);
                    this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Hooks.Root, copySubFolders: false);
                    this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Info.Root, copySubFolders: false);
                    this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Logs.Root, copySubFolders: true);
                    this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Refs.Root, copySubFolders: true);
                    this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Objects.Info.Root, copySubFolders: false);

                    this.CopyEsentDatabase <long, GVFltCallbacks.BackgroundGitUpdate>(
                        enlistment.DotGVFSRoot,
                        Path.Combine(archiveFolderPath, GVFSConstants.DotGVFS.Root),
                        GVFSConstants.DatabaseNames.BackgroundGitUpdates);
                    this.CopyEsentDatabase <string, string>(
                        enlistment.DotGVFSRoot,
                        Path.Combine(archiveFolderPath, GVFSConstants.DotGVFS.Root),
                        GVFSConstants.DatabaseNames.PlaceholderList);
                    this.CopyEsentDatabase <string, long>(
                        enlistment.DotGVFSRoot,
                        Path.Combine(archiveFolderPath, GVFSConstants.DotGVFS.Root),
                        GVFSConstants.DatabaseNames.BlobSizes);
                    this.CopyEsentDatabase <string, string>(
                        enlistment.DotGVFSRoot,
                        Path.Combine(archiveFolderPath, GVFSConstants.DotGVFS.Root),
                        GVFSConstants.DatabaseNames.RepoMetadata);

                    this.WriteMessage("Copying GVFS.Service logs and data...");
                    this.CopyAllFiles(
                        GVFSService.GetServiceDataRoot(string.Empty),
                        archiveFolderPath,
                        this.ServiceName,
                        copySubFolders: true);

                    this.WriteMessage(string.Empty);
                    this.WriteMessage("Remounting GVFS...");
                    ReturnCode mountResult = this.RunAndRecordGVFSVerb <MountVerb>(archiveFolderPath, "gvfs_mount.txt");
                    if (mountResult == ReturnCode.Success)
                    {
                        this.WriteMessage("Mount succeeded");
                    }
                    else
                    {
                        this.WriteMessage("Failed to remount. The reason for failure was captured.");
                    }

                    this.CopyAllFiles(enlistment.DotGVFSRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGVFS.Root), "logs", copySubFolders: false);
                }

            string zipFilePath = archiveFolderPath + ".zip";

            ZipFile.CreateFromDirectory(archiveFolderPath, zipFilePath);
            PhysicalFileSystem.RecursiveDelete(archiveFolderPath);

            this.Output.WriteLine();
            this.Output.WriteLine("Diagnostics complete. All of the gathered info, as well as all of the output above, is captured in");
            this.Output.WriteLine(zipFilePath);
            this.Output.WriteLine();
            this.Output.WriteLine("If you are experiencing an issue, please email the GVFS team with your repro steps and include this zip file.");
        }
        public async Task <bool> Download(string modDir)
        {
            if (updateInfo.Name == "BloonsTD6 Mod Helper")
            {
                Process.Start(updateInfo.LatestURL);
                MelonLogger.Msg("For the moment, the mod helper can't directly update itself");
                return(false);
            }


            string downloadURL;

            if (updateInfo.GithubReleaseURL != "")
            {
                var releaseInfo = await GetLatestReleaseAsync();

                downloadURL = releaseInfo.Assets.Select(asset => asset.BrowserDownloadUrl.OriginalString)
                              .FirstOrDefault(s => s.EndsWith(".dll") || s.EndsWith(".zip"));
            }
            else
            {
                downloadURL = updateInfo.LatestURL;
            }

            if (downloadURL == "" || downloadURL == default)
            {
                return(false);
            }


            if (!string.IsNullOrEmpty(updateInfo.Location))
            {
                try
                {
                    File.Delete(updateInfo.Location);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            var fileName = downloadURL.Substring(downloadURL.LastIndexOf("/", StringComparison.Ordinal));

            if (fileName.Contains("?"))
            {
                fileName = fileName.Substring(0, fileName.IndexOf("?", StringComparison.Ordinal));
            }

            var response = await client.GetAsync(downloadURL);

            string newFile = $"{modDir}\\{fileName}";

            using (var fs = new FileStream(newFile, FileMode.Create))
            {
                await response.Content.CopyToAsync(fs);
            }

            var helperDir = $"{modDir}\\{Assembly.GetExecutingAssembly().GetName().Name}";

            if (fileName.EndsWith(".zip"))
            {
                var zipTemp = $"{helperDir}\\Zip Temp";
                if (Directory.Exists(zipTemp))
                {
                    Directory.Delete(zipTemp, true);
                }
                Directory.CreateDirectory(zipTemp);
                ZipFile.ExtractToDirectory(newFile, zipTemp);

                foreach (var enumerateFile in Directory.EnumerateFiles(zipTemp))
                {
                    var name       = Path.GetFileName(enumerateFile);
                    var targetFile = Path.Combine(modDir, name);
                    if (File.Exists(targetFile))
                    {
                        File.Delete(targetFile);
                    }
                    File.Copy(enumerateFile, targetFile);
                    File.Delete(enumerateFile);
                }
                File.Delete(newFile);
            }

            return(true);
        }
Beispiel #46
0
 /// <summary>
 ///     The path to the archive to open, specified as a relative or absolute path. A relative path is interpreted as
 ///     relative to the current working directory.
 /// </summary>
 /// <param name="this">
 ///     The path to the archive to open, specified as a relative or absolute path. A relative path is
 ///     interpreted as relative to the current working directory.
 /// </param>
 /// <returns>The opened zip archive.</returns>
 public static ZipArchive OpenReadZipFile(this FileInfo @this)
 {
     return(ZipFile.OpenRead(@this.FullName));
 }
Beispiel #47
0
        /// <summary>
        /// Download dataDelivery.
        /// </summary>
        /// <param name="downloadFolder">Pass string.Empty to download to auto-temporary folder.</param>
        public bool BeginDownload(bool extractDownloadResult, string downloadFolder)
        {
            lock (this)
            {
                if (_isDownloading || _downloadedTempFilesPaths.Count > 0 || _downloadProgressPercentage != 0)
                {
                    SystemMonitor.Warning("Online data entry downloading or data not processed.");
                    return(false);
                }

                _isDownloading = true;

                string operationTempFolder = downloadFolder;

                if (string.IsNullOrEmpty(operationTempFolder))
                {
                    operationTempFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
                }

                if (Directory.Exists(operationTempFolder) == false)
                {
                    Directory.CreateDirectory(operationTempFolder);
                }

                string localDownloadFilePath = Path.Combine(operationTempFolder, Path.GetFileName(_uri));

                WebClient client = new WebClient();
                client.DownloadFileCompleted += delegate(object sender, AsyncCompletedEventArgs e)
                {
                    _downloadProgressPercentage = 100;
                    _downloadedTempFilesPaths.Clear();
                    _isDownloading = false;

                    if (extractDownloadResult && Path.GetExtension(localDownloadFilePath).ToLower() == ".zip")
                    {// Unzip the downloaded file.
                        try
                        {
                            ZipFile file = new ZipFile(localDownloadFilePath);
                            file.ExtractAll(operationTempFolder, true);
                            foreach (string fileName in file.EntryFileNames)
                            {
                                _downloadedTempFilesPaths.Add(Path.Combine(operationTempFolder, fileName));
                            }
                        }
                        catch (Exception ex)
                        {
                            _downloadProgressPercentage = 0;
                            SystemMonitor.OperationError("Failed to extract file from [" + _uri + ", " + ex.Message + "].");
                        }
                    }
                    else
                    {
                        _downloadedTempFilesPaths.Add(localDownloadFilePath);
                    }

                    if (DataDownloadedEvent != null)
                    {
                        DataDownloadedEvent(this);
                    }
                };

                client.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e)
                {
                    _downloadProgressPercentage = e.ProgressPercentage;

                    if (DataDownloadUpdateEvent != null)
                    {
                        DataDownloadUpdateEvent(this);
                    }
                };

                client.DownloadFileAsync(new Uri(_uri), localDownloadFilePath);
            }

            return(true);
        }
Beispiel #48
0
 /// <summary>Extracts all the files in the specified zip archive to a directory on the file system.</summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="destinationDirectory">Pathname of the destination directory.</param>
 public static void ExtractZipFileToDirectory(this FileInfo @this, DirectoryInfo destinationDirectory)
 {
     ZipFile.ExtractToDirectory(@this.FullName, destinationDirectory.FullName);
 }
Beispiel #49
0
        protected async Task <Response> Process2(string controllerName, string fileName, string folderName, string outFileExtension, bool createZip, ActionDelegate action)
        {
            string logMsg       = "ControllerName: " + controllerName + " FileName: " + fileName + " OutFileExtension: " + outFileExtension;
            string guid         = folderName;
            string sourceFolder = AppSettings.WorkingDirectory + folderName;

            fileName = sourceFolder + "/" + fileName;

            string outfileName = Path.GetFileNameWithoutExtension(fileName) + outFileExtension;
            string outPath     = AppSettings.OutputDirectory + "/" + guid;

            string zipOutfileName = Path.GetFileNameWithoutExtension(fileName) + ".zip";
            string zipOutPath     = AppSettings.OutputDirectory + zipOutfileName;
            string zipOutFolder   = AppSettings.OutputDirectory + guid;

            string statusValue     = "OK";
            int    statusCodeValue = 200;

            try
            {
                if (System.IO.File.Exists(zipOutPath))
                {
                    System.IO.File.Delete(zipOutPath);
                }

                if (!createZip)
                {
                    if (!Directory.Exists(outPath))
                    {
                        Directory.CreateDirectory(outPath);
                    }
                }
                outPath += "/" + outfileName;
                action(fileName, outPath, zipOutFolder);

                if (createZip)
                {
                    outfileName = Path.GetFileNameWithoutExtension(fileName) + outFileExtension;
                    outPath     = zipOutFolder + "/" + outfileName;
                    Directory.CreateDirectory(zipOutFolder);
                }

                if (createZip)
                {
                    ZipFile.CreateFromDirectory(zipOutFolder, zipOutPath);
                    Directory.Delete(zipOutFolder, true);
                    outfileName = zipOutfileName;
                }

                try
                {
                    Directory.Delete(sourceFolder, true);
                }
                catch
                { }
            }
            catch (Exception exc)
            {
                statusValue     = "500 " + exc.Message;
                statusCodeValue = 500;
            }

            return(await Task.FromResult(new Response
            {
                FileName = (createZip ? outfileName : folderName + "/" + outfileName),
                Status = statusValue,
                StatusCode = statusCodeValue
            }));
        }
Beispiel #50
0
 /// <summary>
 ///     Extracts all the files in the specified zip archive to a directory on the file system
 ///     and uses the specified character encoding for entry names.
 /// </summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="destinationDirectory">Pathname of the destination directory.</param>
 /// <param name="entryNameEncoding">
 ///     The encoding to use when reading or writing entry names in
 ///     this archive. Specify a value for this parameter only when an encoding is required for
 ///     interoperability with zip archive tools and libraries that do not support UTF-8 encoding for
 ///     entry names.
 /// </param>
 public static void ExtractZipFileToDirectory(this FileInfo @this, DirectoryInfo destinationDirectory, Encoding entryNameEncoding)
 {
     ZipFile.ExtractToDirectory(@this.FullName, destinationDirectory.FullName, entryNameEncoding);
 }
        private void Convert_Click(object sender, EventArgs e)
        {
            if (Offset.Text == "")
            {
                Offset.Text = "0";
            }
            if (Author.Text != "" && Title.Text != "" && BPM.Text != "" && Input.Text != "")
            {
                string          data = Input.Text;
                SecureWebClient wc   = new SecureWebClient();
                try
                {
                    while (true)
                    {
                        data = wc.DownloadString(data);
                    }
                }
                catch
                {
                }
                string id        = data.Substring(0, data.IndexOf(','));
                string directory = Directory.GetCurrentDirectory();
                data = data.Replace(id + ",", "");
                string[] newdata = data.Split(',');
                decimal  x;
                decimal  y;
                decimal  x2;
                decimal  y2;
                decimal  time;
                int      i    = 1;
                decimal  xmax = -50;
                decimal  xmin = 50;
                decimal  ymax = -50;
                decimal  ymin = 50;
                int      type;
                int      direction = 0;
                string   xyxy;
                string   filename = "\\" + Author.Text + " - " + Title.Text;
                var      rand     = new Random();
                decimal  offset   = decimal.Parse(Offset.Text);
                try
                {
                    if (!Directory.Exists(directory + filename))
                    {
                        Directory.CreateDirectory(directory + filename);
                    }
                    directory += filename;
                    if (!File.Exists(directory + "\\" + id + ".egg"))
                    {
                        using (wc = new SecureWebClient())
                        {
                            wc.DownloadFile("https://assetdelivery.roblox.com/v1/asset/?id=" + id, directory + "\\" + id + ".egg");
                        }
                    }
                    if (!File.Exists(directory + "\\cover.jpg"))
                    {
                        using (wc = new SecureWebClient())
                        {
                            wc.DownloadFile("https://raw.githubusercontent.com/Avibah/Sound-Space-Multi-Tool/accompanying-files/cover.jpeg", directory + "\\cover.jpg");
                        }
                    }
                    try
                    {
                        decimal bpm = decimal.Parse(BPM.Text);
                        if (bpm == 0)
                        {
                            bpm = 100;
                        }
                        foreach (var line in newdata)
                        {
                            var lineSplit = Regex.Matches(line, "([^|]+)");
                            x = decimal.Parse(lineSplit[0].Value);
                            y = decimal.Parse(lineSplit[1].Value);
                            if (x > xmax)
                            {
                                xmax = x;
                            }
                            if (x < xmin)
                            {
                                xmin = x;
                            }
                            if (y > ymax)
                            {
                                ymax = y;
                            }
                            if (y < ymin)
                            {
                                ymin = y;
                            }
                        }
                        xmax -= xmin;
                        ymax -= ymin;
                        if (xmax == 0)
                        {
                            xmax = 1;
                        }
                        if (ymax == 0)
                        {
                            ymax = 1;
                        }
                        string output = "{\"_version\":\"2.0.0\",\"_customData\":{\"_time\":0,\"_BPMChanges\":[],\"_bookmarks\":[]},\"_events\":[],\"_notes\":[";
                        foreach (var line in newdata)
                        {
                            if (i != 1)
                            {
                                output += ",";
                            }
                            var lineSplit = Regex.Matches(line, "([^|]+)");
                            x    = decimal.Parse(lineSplit[0].Value);
                            y    = decimal.Parse(lineSplit[1].Value);
                            time = decimal.Parse(lineSplit[2].Value);
                            if (ApplyOffset.Checked == true)
                            {
                                time += offset;
                            }
                            x -= xmin;
                            x  = x * 2 / xmax;
                            y -= ymin;
                            y  = y * 2 / ymax;
                            if (Directions.Checked == true)
                            {
                                if (i >= newdata.Length)
                                {
                                    xyxy = Math.Round(x).ToString() + Math.Round(y).ToString();
                                    var lineSplit2 = Regex.Matches(newdata[i - 2], "([^|]+)");
                                    x2    = decimal.Parse(lineSplit2[0].Value);
                                    y2    = decimal.Parse(lineSplit2[1].Value);
                                    xyxy += Math.Round(x2).ToString() + Math.Round(y2).ToString();
                                }
                                else
                                {
                                    xyxy = Math.Round(x).ToString() + Math.Round(y).ToString();
                                    var lineSplit2 = Regex.Matches(newdata[i], "([^|]+)");
                                    x2    = decimal.Parse(lineSplit2[0].Value);
                                    y2    = decimal.Parse(lineSplit2[1].Value);
                                    xyxy += Math.Round(x2).ToString() + Math.Round(y2).ToString();
                                }
                                switch (xyxy)
                                {
                                case "2000":
                                case "2010":
                                case "2101":
                                case "2111":
                                case "2202":
                                case "2212":
                                case "1000":
                                case "1101":
                                case "1202":
                                    direction = 2;
                                    break;

                                case "0001":
                                case "0002":
                                case "1011":
                                case "1012":
                                case "2021":
                                case "2022":
                                case "0102":
                                case "1112":
                                case "2122":
                                    direction = 1;
                                    break;

                                case "0200":
                                case "0201":
                                case "1210":
                                case "1211":
                                case "2220":
                                case "2221":
                                case "0100":
                                case "1110":
                                case "2120":
                                    direction = 0;
                                    break;

                                case "0210":
                                case "0220":
                                case "0211":
                                case "0221":
                                case "1120":
                                case "1221":
                                case "1220":
                                case "0110":
                                case "0120":
                                    direction = 5;
                                    break;

                                case "2200":
                                case "2201":
                                case "2211":
                                case "2210":
                                case "1100":
                                case "2100":
                                case "2110":
                                case "1200":
                                case "1201":
                                    direction = 4;
                                    break;

                                case "0010":
                                case "0020":
                                case "0111":
                                case "0121":
                                case "0212":
                                case "0222":
                                case "1020":
                                case "1121":
                                case "1222":
                                    direction = 3;
                                    break;

                                case "0000":
                                case "0101":
                                case "0202":
                                case "1010":
                                case "1111":
                                case "1212":
                                case "2020":
                                case "2121":
                                case "2222":
                                    direction = 8;
                                    break;

                                case "0011":
                                case "0021":
                                case "0012":
                                case "0022":
                                case "0112":
                                case "0122":
                                case "1021":
                                case "1022":
                                case "1122":
                                    direction = 7;
                                    break;

                                case "2011":
                                case "2001":
                                case "2012":
                                case "2002":
                                case "1001":
                                case "1002":
                                case "1102":
                                case "2112":
                                case "2102":
                                    direction = 6;
                                    break;
                                }
                            }
                            else
                            {
                                direction = 8;
                            }
                            x = x * -1 + 2;
                            if (rand.Next(0, 2) == 1)
                            {
                                x *= 2000;
                            }
                            else
                            {
                                x = x * 2000 + 1000;
                            }
                            if (i % 2 == 0)
                            {
                                type = 1;
                            }
                            else
                            {
                                type = 0;
                            }
                            y     = y * 1000 + 1000;
                            x     = Math.Round(x);
                            y     = Math.Round(y);
                            time /= 60000 / bpm;
                            time  = Math.Round(time, 6);

                            output += "{\"_time\":" + time + ",\"_lineIndex\":" + x + ",\"_lineLayer\":" + y + ",\"_type\":" + type + ",\"_cutDirection\":" + direction + "}";
                            i      += 1;
                        }
                        output += "],\"_obstacles\":[]}";
                        using (FileStream fs = File.Create(directory + "\\" + "Easy.dat"))
                        {
                            byte[] info = new UTF8Encoding(true).GetBytes(output);
                            fs.Write(info, 0, info.Length);
                        }
                        output = "{\n  \"_version\": \"2.0.0\",\n  \"_songName\": \"" + Title.Text + "\",\n  \"_songSubName\": \"\",\n  \"_songAuthorName\": \"" + Author.Text + "\",\n  \"_levelAuthorName\": \"djk\",\n  \"_beatsPerMinute\": " + BPM.Text + ",\n  \"_songTimeOffset\": 0,\n  \"_shuffle\": 0,\n  \"_shufflePeriod\": 0.5,\n  \"_previewStartTime\": 20,\n  \"_previewDuration\": 10,\n  \"_songFilename\": \"" + id + ".egg\",\n  \"_coverImageFilename\": \"cover.jpg\",\n  \"_environmentName\": \"BigMirrorEnvironment\",\n  \"_difficultyBeatmapSets\": [\n    {\n      \"_beatmapCharacteristicName\": \"Standard\",\n      \"_difficultyBeatmaps\": [\n        {\n          \"_difficulty\": \"Easy\",\n          \"_difficultyRank\": 1,\n          \"_beatmapFilename\": \"Easy.dat\",\n          \"_noteJumpMovementSpeed\": 18,\n          \"_noteJumpStartBeatOffset\": 0,\n          \"_customData\": {\n            \"_requirements\": [\n              \"Mapping Extensions\"\n            ]\n          }\n        }\n      ]\n    }\n  ]\n}";
                        using (FileStream fs = File.Create(directory + "\\" + "info.dat"))
                        {
                            byte[] info = new UTF8Encoding(true).GetBytes(output);
                            fs.Write(info, 0, info.Length);
                        }
                        string zipPath = directory.Replace(filename, "") + filename + ".zip";
                        if (File.Exists(directory.Replace(filename, "") + filename + ".zip"))
                        {
                            File.Delete(directory.Replace(filename, "") + filename + ".zip");
                        }
                        ZipFile.CreateFromDirectory(directory, zipPath);
                        Directory.Delete(directory, true);
                        MessageBox.Show("Map successfully converted!");
                    }
                    catch
                    {
                    }
                }
                catch
                {
                    MessageBox.Show("Failed to download audio with id: " + id, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Make sure to fill in every empty box with the appropriate information");
            }
        }
Beispiel #52
0
 /// <summary>
 ///     Creates a zip archive that contains the files and directories from the specified directory, uses the specified
 ///     compression level and character encoding for entry names, and optionally includes the base directory.
 /// </summary>
 /// <param name="this">
 ///     The path to the directory to be archived, specified as a relative or absolute path. A relative path
 ///     is interpreted as relative to the current working directory.
 /// </param>
 /// <param name="destinationArchiveFileName">
 ///     The path of the archive to be created, specified as a relative or absolute
 ///     path. A relative path is interpreted as relative to the current working directory.
 /// </param>
 /// <param name="compressionLevel">
 ///     One of the enumeration values that indicates whether to emphasize speed or compression
 ///     effectiveness when creating the entry.
 /// </param>
 /// <param name="includeBaseDirectory">
 ///     true to include the directory name from sourceDirectoryName at the root of the
 ///     archive; false to include only the contents of the directory.
 /// </param>
 /// <param name="entryNameEncoding">
 ///     The encoding to use when reading or writing entry names in this archive. Specify a
 ///     value for this parameter only when an encoding is required for interoperability with zip archive tools and
 ///     libraries that do not support UTF-8 encoding for entry names.
 /// </param>
 public static void CreateZipFile(this DirectoryInfo @this, string destinationArchiveFileName, CompressionLevel compressionLevel, bool includeBaseDirectory, Encoding entryNameEncoding)
 {
     ZipFile.CreateFromDirectory(@this.FullName, destinationArchiveFileName, compressionLevel, includeBaseDirectory, entryNameEncoding);
 }
Beispiel #53
0
    // Load a saved game, does nothing if file does not exist
    public static void Load()
    {
        Game game = Game.Get();

        try
        {
            if (File.Exists(SaveFile()))
            {
                if (!Directory.Exists(Path.GetTempPath() + "/Valkyrie"))
                {
                    Directory.CreateDirectory(Path.GetTempPath() + "/Valkyrie");
                }
                if (!Directory.Exists(Path.GetTempPath() + "/Valkyrie/Load"))
                {
                    Directory.CreateDirectory(Path.GetTempPath() + "/Valkyrie/Load");
                }

                Directory.Delete(Path.GetTempPath() + "/Valkyrie/Load", true);
                ZipFile zip = ZipFile.Read(SaveFile());
                zip.ExtractAll(Path.GetTempPath() + "/Valkyrie/Load");
                zip.Dispose();

                // Check that quest in save is valid
                QuestData.Quest q = new QuestData.Quest(Path.GetTempPath() + "/Valkyrie/Load/quest");
                if (!q.valid)
                {
                    ValkyrieDebug.Log("Error: save contains unsupported quest version." + System.Environment.NewLine);
                    Destroyer.MainMenu();
                    return;
                }

                string data = File.ReadAllText(Path.GetTempPath() + "/Valkyrie/Load/save.ini");

                IniData saveData = IniRead.ReadFromString(data);

                saveData.data["Quest"]["path"] = Path.GetTempPath() + "/Valkyrie/Load/quest/quest.ini";

                saveData.Get("Quest", "valkyrie");

                if (VersionNewer(game.version, saveData.Get("Quest", "valkyrie")))
                {
                    ValkyrieDebug.Log("Error: save is from a future version." + System.Environment.NewLine);
                    Destroyer.MainMenu();
                    return;
                }

                if (!VersionNewerOrEqual(minValkyieVersion, saveData.Get("Quest", "valkyrie")))
                {
                    ValkyrieDebug.Log("Error: save is from an old unsupported version." + System.Environment.NewLine);
                    Destroyer.MainMenu();
                    return;
                }

                Destroyer.Dialog();

                // Restart contend data so we can select from save
                game.cd = new ContentData(game.gameType.DataDirectory());
                // Check if we found anything
                if (game.cd.GetPacks().Count == 0)
                {
                    ValkyrieDebug.Log("Error: Failed to find any content packs, please check that you have them present in: " + game.gameType.DataDirectory() + System.Environment.NewLine);
                    Application.Quit();
                }

                game.cd.LoadContentID("");
                // Load the base content

                // Load content that the save game uses
                Dictionary <string, string> packs = saveData.Get("Packs");
                foreach (KeyValuePair <string, string> kv in packs)
                {
                    game.cd.LoadContentID("");
                    game.cd.LoadContentID(kv.Key);
                }

                // This loads the game
                new Quest(saveData);

                // Draw things on the screen
                game.heroCanvas.SetupUI();
                game.heroCanvas.UpdateImages();
                game.heroCanvas.UpdateStatus();

                if (game.gameType.DisplayMorale())
                {
                    game.moraleDisplay = new MoraleDisplay();
                }
                if (!game.gameType.DisplayHeroes())
                {
                    game.heroCanvas.Clean();
                }

                // Create the menu button
                new MenuButton();
                new LogButton();
                game.stageUI = new NextStageButton();
            }
        }
        catch (System.Exception e)
        {
            ValkyrieDebug.Log("Error: Unable to open save file: " + SaveFile() + " " + e.Message);
            Application.Quit();
        }
    }
Beispiel #54
0
 /// <summary>
 ///     Creates a zip archive that contains the files and directories from the specified
 ///     directory.
 /// </summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="destinationArchiveFile">
 ///     The path of the archive to be created, specified as a
 ///     relative or absolute path. A relative path is interpreted as relative to the current working
 ///     directory.
 /// </param>
 public static void CreateZipFile(this DirectoryInfo @this, FileInfo destinationArchiveFile)
 {
     ZipFile.CreateFromDirectory(@this.FullName, destinationArchiveFile.FullName);
 }
Beispiel #55
0
        /// <summary>
        /// Handles the bulk of the work for submitting the job to the cloud.
        /// Zips up ApsimX (if necessary), uploads tools and ApsimX,
        /// </summary>
        /// <param name="e">Event arg, containing the job parameters</param>
        private void SubmitJob_DoWork(object o, DoWorkEventArgs e)
        {
            JobParameters jp = (JobParameters)e.Argument;

            jp.JobId                       = Guid.NewGuid();
            jp.CoresPerProcess             = 1;
            jp.JobManagerShouldSubmitTasks = true;
            jp.AutoScale                   = true;
            jp.PoolMaxTasksPerVM           = 16;
            string tmpZip = "";

            SetAzureMetaData("job-" + jp.JobId, "Owner", Environment.UserName.ToLower());

            // if jp.ApplicationPackagePath is a directory it will need to be zipped up
            if (Directory.Exists(jp.ApplicationPackagePath))
            {
                view.Status = "Zipping APSIM";

                tmpZip = Path.Combine(Path.GetTempPath(), "Apsim-tmp-X-" + Environment.UserName.ToLower() + ".zip");
                if (File.Exists(tmpZip))
                {
                    File.Delete(tmpZip);
                }

                if (CreateApsimXZip(jp.ApplicationPackagePath, tmpZip) > 0)
                {
                    view.Status = "Cancelled";
                    return;
                }

                jp.ApplicationPackagePath    = tmpZip;
                jp.ApplicationPackageVersion = Path.GetFileName(tmpZip).Substring(Path.GetFileName(tmpZip).IndexOf('-') + 1);
            }

            // add current job to the list of jobs

            // TODO : do we actually need/use the APSIMJob class?
            APSIMJob job = new APSIMJob(jp.JobDisplayName, "", jp.ApplicationPackagePath, jp.ApplicationPackageVersion, jp.Recipient, batchAuth, storageAuth, PoolSettings.FromConfiguration());

            job.PoolInfo.MaxTasksPerVM = jp.PoolMaxTasksPerVM;
            job.PoolInfo.VMCount       = jp.PoolVMCount;


            // upload tools such as 7zip, AzCopy, CMail, etc.

            view.Status = "Checking tools";

            string executableDirectory = GetExecutableDirectory();
            string toolsDir            = Path.Combine(executableDirectory, "tools");

            if (!Directory.Exists(toolsDir))
            {
                ShowErrorMessage("Tools Directory not found: " + toolsDir);
            }

            foreach (string filePath in Directory.EnumerateFiles(toolsDir))
            {
                UploadFileIfNeeded("tools", filePath);
            }

            if (jp.Recipient.Length > 0)
            {
                try
                {
                    // Store a config file into the job directory that has the e-mail config

                    string tmpConfig = Path.Combine(Path.GetTempPath(), settingsFileName);
                    using (StreamWriter file = new StreamWriter(tmpConfig))
                    {
                        file.WriteLine("EmailRecipient=" + jp.Recipient);
                        file.WriteLine("EmailSender=" + AzureSettings.Default["EmailSender"]);
                        file.WriteLine("EmailPW=" + AzureSettings.Default["EmailPW"]);
                    }

                    UploadFileIfNeeded("job-" + jp.JobId, tmpConfig);
                    File.Delete(tmpConfig);
                }
                catch (Exception err)
                {
                    ShowError(new Exception("Error writing to settings file; you may not receive an email upon job completion: ", err));
                }
            }

            // upload job manager
            UploadFileIfNeeded("jobmanager", Path.Combine(executableDirectory, "azure-apsim.exe"));



            // upload apsim
            view.Status = "Uploading APSIM Next Generation";

            UploadFileIfNeeded("apsim", jp.ApplicationPackagePath);


            // generate model files

            view.Status = "Generating model files";
            if (!Directory.Exists(jp.ModelPath))
            {
                Directory.CreateDirectory(jp.ModelPath);
            }

            try
            {
                // copy weather files to models directory to be zipped up
                foreach (Models.Weather child in Apsim.ChildrenRecursively(model).OfType <Models.Weather>())
                {
                    if (Path.GetDirectoryName(child.FullFileName) != Path.GetDirectoryName(presenter.ApsimXFile.FileName))
                    {
                        presenter.MainPresenter.ShowError("Weather file must be in the same directory as .apsimx file: " + child.FullFileName);
                        view.Status = "Cancelled";
                        return;
                    }
                    string sourceFile = child.FullFileName;
                    string destFile   = Path.Combine(jp.ModelPath, child.FileName);
                    if (!File.Exists(destFile))
                    {
                        File.Copy(sourceFile, destFile);
                    }
                    ;
                }
                // Generate .apsimx files, and if any errors are encountered, abort the job submission process.
                if (!presenter.GenerateApsimXFiles(model, jp.ModelPath))
                {
                    view.Status = "Cancelled";
                    return;
                }
            }
            catch (Exception err)
            {
                presenter.MainPresenter.ShowError(err);
                return;
            }

            tmpZip = "";

            // zip up models directory
            if (Directory.Exists(jp.ModelPath)) // this test may be unnecessary
            {
                tmpZip = GetTempFileName("Model-", ".zip", true);
                ZipFile.CreateFromDirectory(jp.ModelPath, tmpZip, CompressionLevel.Fastest, false);
                jp.ModelPath = tmpZip;
            }

            // upload models

            view.Status         = "Uploading models";
            job.ModelZipFileSas = uploader.UploadFile(jp.ModelPath, jp.JobId.ToString(), Path.GetFileName(jp.ModelPath));

            // clean up temporary model files
            if (File.Exists(tmpZip))
            {
                File.Delete(tmpZip);
            }
            if (!jp.SaveModelFiles)
            {
                if (Directory.Exists(jp.ModelPath))
                {
                    Directory.Delete(jp.ModelPath);
                }
            }

            view.Status = "Submitting Job";



            // submit job
            try
            {
                CloudJob cloudJob = batchCli.JobOperations.CreateJob(jp.JobId.ToString(), GetPoolInfo(job.PoolInfo));
                cloudJob.DisplayName        = job.DisplayName;
                cloudJob.JobPreparationTask = job.ToJobPreparationTask(jp.JobId, storageAccount.CreateCloudBlobClient());
                cloudJob.JobReleaseTask     = job.ToJobReleaseTask(jp.JobId, storageAccount.CreateCloudBlobClient());
                cloudJob.JobManagerTask     = job.ToJobManagerTask(jp.JobId, storageAccount.CreateCloudBlobClient(), jp.JobManagerShouldSubmitTasks, jp.AutoScale);

                cloudJob.Commit();
            }
            catch (Exception err)
            {
                ShowError(err);
            }

            view.Status = "Job Successfully submitted";

            if (jp.AutoDownload)
            {
                AzureResultsDownloader dl = new AzureResultsDownloader(jp.JobId, jp.JobDisplayName, jp.OutputDir, null, true, jp.Summarise, true, true, true);
                dl.DownloadResults(true);
            }
        }
 private void Unzip()
 {
     Console.WriteLine("Unzipping tools");
     ZipFile.ExtractToDirectory(_zipPath, InstallPath, true);
 }
 public static IEnumerable <ZipArchiveEntry> EnumerateZip(string root)
 {
     using (var zip = ZipFile.OpenRead(root)) {
         return(zip.Entries.ToList());
     }
 }
Beispiel #58
0
        /// <summary>
        /// Extracts the zip.
        /// </summary>
        /// <param name="zip">The zip.</param>
        /// <param name="rootFolder">The root folder.</param>
        /// <param name="newFolder">The new folder.</param>
        /// <param name="matchPath">The match path.</param>
        private void ExtractZip(string zip, string rootFolder, string newFolder, string matchPath)
        {
            try {
                long totalEntries = 0;
                using (ZipFile z = new ZipFile(zip)) {
                    totalEntries = z.Count;
                    this.downloadProgress.SetMaximum((int)z.Count);
                    this.downloadProgress.SetMinimum(0);
                    this.downloadProgress.SetValue(0);
                    z.Close( );
                }
                using (FileStream zfs = new FileStream(zip, FileMode.Open, FileAccess.Read)) {
                    long currentEntryIndex = 0;

                    using (ZipInputStream zis = new ZipInputStream(zfs)) {
                        ZipEntry ze = zis.GetNextEntry( );
                        while (ze != null)
                        {
                            string entryPath         = Path.GetDirectoryName(ze.Name).Replace(rootFolder, newFolder);
                            string fullDirectoryPath = Path.Combine(SdkPath, entryPath);

                            string fileName = Path.GetFileName(ze.Name);
                            string fullPath = Path.Combine(fullDirectoryPath, fileName);

                            if (!fullPath.Contains(matchPath))
                            {
                                ze = zis.GetNextEntry( );
                                currentEntryIndex++;
                                continue;
                            }

                            if (!Directory.Exists(fullDirectoryPath))
                            {
                                Directory.CreateDirectory(fullDirectoryPath);
                            }

                            this.downloadStatus.SetText(string.Format(CultureInfo.InvariantCulture, Properties.Resources.ExtractingFileFormat, ze.Name));
                            if (ze.IsFile)
                            {
                                using (FileStream fs = new FileStream(fullPath, FileMode.Create, FileAccess.Write, FileShare.Read)) {
                                    int    bread  = 0;
                                    byte[] buffer = new byte[2048];
                                    while ((bread = zis.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        fs.Write(buffer, 0, bread);
                                    }
                                    fs.Close( );
                                }
                            }
                            this.downloadProgress.SetValue((int)currentEntryIndex);
                            ze = zis.GetNextEntry( );
                            currentEntryIndex++;
                        }
                        zis.Close( );
                    }
                    zfs.Close( );
                    this.downloadProgress.SetValue(0);
                    this.downloadStatus.SetText(string.Empty);
                }
            } catch (Exception ex) {
                throw;
            }
        }
Beispiel #59
0
        public void UpdateCommentOnlyOnDisk()
        {
            string tempFile = GetTempFilePath();

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

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
            if (File.Exists(tempFile))
            {
                File.Delete(tempFile);
            }

            using (ZipFile testFile = ZipFile.Create(tempFile))
            {
                testFile.BeginUpdate();
                testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored);
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(tempFile))
            {
                Assert.IsTrue(testFile.TestArchive(true));
                Assert.AreEqual("", testFile.ZipFileComment);

                testFile.BeginUpdate(new DiskArchiveStorage(testFile, FileUpdateMode.Direct));
                testFile.SetComment("Here is my comment");
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(tempFile))
            {
                Assert.IsTrue(testFile.TestArchive(true));
                Assert.AreEqual("Here is my comment", testFile.ZipFileComment);
            }
            File.Delete(tempFile);

            // Variant using indirect updating.
            using (ZipFile testFile = ZipFile.Create(tempFile))
            {
                testFile.BeginUpdate();
                testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored);
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(tempFile))
            {
                Assert.IsTrue(testFile.TestArchive(true));
                Assert.AreEqual("", testFile.ZipFileComment);

                testFile.BeginUpdate();
                testFile.SetComment("Here is my comment");
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(tempFile))
            {
                Assert.IsTrue(testFile.TestArchive(true));
                Assert.AreEqual("Here is my comment", testFile.ZipFileComment);
            }
            File.Delete(tempFile);
        }
Beispiel #60
0
 public ZipFileWrapper(ZipFile file)
 {
     _file = file;
 }