/// <summary>
		/// Performs the actual mod preparation work.
		/// </summary>
		/// <param name="p_objArgs">The task arguments.</param>
		/// <returns>Always <c>null</c>.</returns>
		protected override object DoWork(object[] p_objArgs)
		{
			string strFileName = (string)p_objArgs[0];
			Project prjModProject = (Project)p_objArgs[1];
			/*
			 * 1) Create file dictionary
			 * 2) Create info.xml
			 * 3) Create screenshot
			 * 4) Create readme
			 * 5) Create XML Script
			 * 6) Pack mod
			 * 7) Clean up
			 */

			string strTmpDirectory = null;
			SevenZipCompressor szcCompressor = null;
			try
			{
				ItemMessage = "Finding Mod Files...";
				ItemProgressMaximum = prjModProject.ModFiles.Count;
				ItemProgress = 0;
				Dictionary<string, string> dicFiles = new Dictionary<string, string>();
				foreach (VirtualFileSystemItem vfiItem in prjModProject.ModFiles)
				{
					StepItemProgress();
					if (vfiItem.IsDirectory)
						continue;
					dicFiles[vfiItem.Path] = vfiItem.Source;
				}

				StepOverallProgress();
				if (Status == TaskStatus.Cancelling)
					return null;

				strTmpDirectory = FileUtilities.CreateTempDirectory();

				ItemMessage = "Generating Info File...";
				ItemProgressMaximum = 1;
				ItemProgress = 0;
				string strInfoFilePath = Path.Combine(strTmpDirectory, "info.xml");
				XmlDocument xmlInfo = new XmlDocument();
				xmlInfo.AppendChild(prjModProject.SaveInfo(xmlInfo, false));
				xmlInfo.Save(strInfoFilePath);
				dicFiles[Path.Combine(NexusMod.MetaFolder, "info.xml")] = strInfoFilePath;

				StepOverallProgress();
				if (Status == TaskStatus.Cancelling)
					return null;

				if (prjModProject.Screenshot != null)
				{
					ItemMessage = "Generating Screenshot...";
					ItemProgressMaximum = 1;
					ItemProgress = 0;

					string strScreenshotPath = Path.Combine(strTmpDirectory, "screenshot.jpg");
					strScreenshotPath = Path.ChangeExtension(strScreenshotPath, prjModProject.Screenshot.GetExtension());
					File.WriteAllBytes(strScreenshotPath, prjModProject.Screenshot.Data);
					dicFiles[Path.Combine(NexusMod.MetaFolder, Path.GetFileName(strScreenshotPath))] = strScreenshotPath;

					StepOverallProgress();
					if (Status == TaskStatus.Cancelling)
						return null;
				}

				if (prjModProject.ModReadme != null)
				{
					ItemMessage = "Generating Readme...";
					ItemProgressMaximum = 1;
					ItemProgress = 0;

					string strReadmePath = Path.Combine(strTmpDirectory, "readme.txt");
					strReadmePath = Path.ChangeExtension(strReadmePath, prjModProject.ModReadme.Extension);
					File.WriteAllText(strReadmePath, prjModProject.ModReadme.Text);
					dicFiles[Path.Combine(NexusMod.MetaFolder, Path.GetFileName(strReadmePath))] = strReadmePath;

					StepOverallProgress();
					if (Status == TaskStatus.Cancelling)
						return null;
				}

				if (prjModProject.InstallScript != null)
				{
					ItemMessage = "Generating Install Script...";
					ItemProgressMaximum = 1;
					ItemProgress = 0;

					XDocument xmlScript = new XDocument();
					IScriptType stpType = prjModProject.InstallScript.Type;
					XElement xelScript = XElement.Parse(stpType.SaveScript(prjModProject.InstallScript));
					xmlScript.Add(xelScript);

					string strScriptPath = Path.Combine(strTmpDirectory, stpType.FileNames[0]);
					xmlScript.Save(strScriptPath);
					dicFiles[Path.Combine(NexusMod.MetaFolder, stpType.FileNames[0])] = strScriptPath;

					StepOverallProgress();
					if (Status == TaskStatus.Cancelling)
						return null;
				}

				ItemMessage = "Compressing Files...";
				ItemProgressMaximum = dicFiles.Count;
				ItemProgress = 0;

				szcCompressor = new SevenZipCompressor();
				szcCompressor.CompressionLevel = CompressionLevel.Fast;
				szcCompressor.ArchiveFormat = OutArchiveFormat.SevenZip;
				szcCompressor.CompressionMethod = CompressionMethod.Default;
				switch (szcCompressor.ArchiveFormat)
				{
					case OutArchiveFormat.Zip:
					case OutArchiveFormat.GZip:
					case OutArchiveFormat.BZip2:
						szcCompressor.CustomParameters.Add("mt", "on");
						break;
					case OutArchiveFormat.SevenZip:
					case OutArchiveFormat.XZ:
						szcCompressor.CustomParameters.Add("mt", "on");
						szcCompressor.CustomParameters.Add("s", "off");
						break;
				}
				szcCompressor.CompressionMode = CompressionMode.Create;
				szcCompressor.FileCompressionStarted += new EventHandler<FileNameEventArgs>(Compressor_FileCompressionStarted);
				szcCompressor.FileCompressionFinished += new EventHandler<EventArgs>(Compressor_FileCompressionFinished);

				szcCompressor.CompressFileDictionary(dicFiles, strFileName);
			}
			finally
			{
				if (!String.IsNullOrEmpty(strTmpDirectory))
				{
					if (szcCompressor != null)
					{
						szcCompressor = null;
						//this is bad form - really we should be disposing szcCompressor, but
						// we can't as it doesn't implement IDisposable, so we have to rely
						// on the garbage collector the force szcCompressor to release its
						// resources (in this case, file locks)
						System.GC.Collect();
					}
					//this try/catch is just in case the GC doesn't go as expected
					// and szcCompressor didn't release its resources
					try
					{
						FileUtil.ForceDelete(strTmpDirectory);
					}
					catch (IOException)
					{
					}
				}
			}
			return null;
		}
示例#2
0
        private void Deployment_BackgroundThread(object sender, DoWorkEventArgs e)
        {
            var referencedFiles = ModBeingDeployed.GetAllRelativeReferences();

            string archivePath = e.Argument as string;
            //Key is in-archive path, value is on disk path
            var archiveMapping             = new Dictionary <string, string>();
            SortedSet <string> directories = new SortedSet <string>();

            foreach (var file in referencedFiles)
            {
                var path      = Path.Combine(ModBeingDeployed.ModPath, file);
                var directory = Directory.GetParent(path).FullName;
                if (directory.Length <= ModBeingDeployed.ModPath.Length)
                {
                    continue;                                                      //root file or directory.
                }
                directory = directory.Substring(ModBeingDeployed.ModPath.Length + 1);

                //nested folders with no folders
                var    relativeFolders    = directory.Split('\\');
                string buildingFolderList = "";
                foreach (var relativeFolder in relativeFolders)
                {
                    if (buildingFolderList != "")
                    {
                        buildingFolderList += @"\\";
                    }
                    buildingFolderList += relativeFolder;
                    if (directories.Add(buildingFolderList))
                    {
                        archiveMapping[buildingFolderList] = null;
                    }
                }
            }

            archiveMapping.AddRange(referencedFiles.ToDictionary(x => x, x => Path.Combine(ModBeingDeployed.ModPath, x)));

            var compressor = new SevenZip.SevenZipCompressor();

            //compressor.CompressionLevel = CompressionLevel.Ultra;
            compressor.CustomParameters.Add(@"s", @"on");
            if (!MultithreadedCompression)
            {
                compressor.CustomParameters.Add(@"mt", @"off");
            }
            compressor.CustomParameters.Add(@"yx", @"9");
            //compressor.CustomParameters.Add("x", "9");
            compressor.CustomParameters.Add(@"d", @"28");
            string currentDeploymentStep = M3L.GetString(M3L.string_mod);

            compressor.Progressing += (a, b) =>
            {
                //Debug.WriteLine(b.AmountCompleted + "/" + b.TotalAmount);
                ProgressMax   = b.TotalAmount;
                ProgressValue = b.AmountCompleted;
                var now = DateTime.Now;
                if ((now - lastPercentUpdateTime).Milliseconds > ModInstaller.PERCENT_REFRESH_COOLDOWN)
                {
                    //Don't update UI too often. Once per second is enough.
                    string percent = (ProgressValue * 100.0 / ProgressMax).ToString(@"0.00");
                    OperationText         = $@"[{currentDeploymentStep}] {M3L.GetString(M3L.string_deploymentInProgress)} {percent}%";
                    lastPercentUpdateTime = now;
                }
                //Debug.WriteLine(ProgressValue + "/" + ProgressMax);
            };
            compressor.FileCompressionStarted += (a, b) => { Debug.WriteLine(b.FileName); };
            compressor.CompressFileDictionary(archiveMapping, archivePath);
            compressor.CustomParameters.Clear(); //remove custom params as it seems to force LZMA
            compressor.CompressionMode  = CompressionMode.Append;
            compressor.CompressionLevel = CompressionLevel.None;
            currentDeploymentStep       = @"moddesc.ini";
            compressor.CompressFiles(archivePath, new string[]
            {
                Path.Combine(ModBeingDeployed.ModPath, @"moddesc.ini")
            });
            OperationText = M3L.GetString(M3L.string_deploymentSucceeded);
            Utilities.HighlightInExplorer(archivePath);
        }
示例#3
0
        public static byte[] CreateWrappedArchive(string basePath, string[] includes, string[] excludes)
        {
            using (MemoryStream inStream = new MemoryStream()) {
                var zipOut = new SevenZipCompressor();
                zipOut.ArchiveFormat = OutArchiveFormat.Zip;
                zipOut.CompressionLevel = SevenZip.CompressionLevel.None;

                List<string> FileList = new List<string>(Search.FindFiles(
                    basePath, includes, excludes, SearchOption.AllDirectories
                ));

                SevenZipBase.SetLibraryPath(Inits.EnsureBinaries());
                zipOut.CompressFileDictionary(
                    FileList.ToDictionary(f => f.Replace(basePath, null), f => f),
                    inStream
                );

                inStream.Position = 0;

                using (var outStream = new MemoryStream()) {
                    using (var LzmaStream = new LzmaEncodeStream(outStream)) {
                        int byt = 0;
                        while ((byt = inStream.ReadByte()) != -1)
                            LzmaStream.WriteByte((byte)byt);
                    }
                    return outStream.ToArray();
                }
            }
        }
		public void CompressFileDictionaryTest(){
			var tmp = new SevenZipCompressor();
			Dictionary<string, string> fileDict = new Dictionary<string, string>();
			var arch = Path.Combine(tempFolder, TestContext.TestName + ".7z");
			fileDict.Add("ololol.bin", testFile1);
			tmp.FileCompressionStarted += (o, e) =>{
				//TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileName));
			};
			tmp.CompressFileDictionary(fileDict, arch);
		}
示例#5
0
        public void Zip()
        {
            if (_Directories != null)
            {
                SevenZipCompressor.SetLibraryPath(@"C:\\Program Files\\7-Zip\\7z.dll");
                SevenZipCompressor c = new SevenZipCompressor();
                c.DirectoryStructure = true;
                c.PreserveDirectoryRoot = false;
                c.CompressionMode = CompressionMode.Create;
                c.ArchiveFormat = OutArchiveFormat.Zip;
                c.PreserveDirectoryRoot = true;

                c.CompressFileDictionary(_Directories, _Dir.FullName + "\\output.docx");
            }
        }
示例#6
-1
        public static bool Export(string exportPath)
        {
            try
            {
                Set7ZipLibraryPath();

                SevenZipCompressor zip = new SevenZipCompressor();
                zip.ArchiveFormat = OutArchiveFormat.SevenZip;
                zip.CompressionLevel = CompressionLevel.Normal;
                zip.CompressionMethod = CompressionMethod.Lzma2;

                Dictionary<string, string> files = new Dictionary<string, string>();
                if (Program.Settings.ExportSettings)
                {
                    AddFileToDictionary(files, Program.ApplicationConfigFilePath);
                    AddFileToDictionary(files, Program.HotkeysConfigFilePath);
                    AddFileToDictionary(files, Program.UploadersConfigFilePath);
                    AddFileToDictionary(files, Program.GreenshotImageEditorConfigFilePath);
                }

                if (Program.Settings.ExportHistory)
                {
                    AddFileToDictionary(files, Program.HistoryFilePath);
                }

                if (Program.Settings.ExportLogs)
                {
                    foreach (string file in Directory.GetFiles(Program.LogsFolder, "*.txt", SearchOption.TopDirectoryOnly))
                    {
                        AddFileToDictionary(files, file, Path.GetFileName(Program.LogsFolder));
                    }
                }

                zip.CompressFileDictionary(files, exportPath);

                return true;
            }
            catch (Exception e)
            {
                DebugHelper.WriteException(e);
                MessageBox.Show("Error while exporting backup:\r\n\r\n" + e, "ShareX - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return false;
        }