AddDirectory() public method

Adds the contents of a filesystem directory to a Zip file archive.

The name of the directory may be a relative path or a fully-qualified path. Any files within the named directory are added to the archive. Any subdirectories within the named directory are also added to the archive, recursively.

Top-level entries in the named directory will appear as top-level entries in the zip archive. Entries in subdirectories in the named directory will result in entries in subdirectories in the zip archive.

If you want the entries to appear in a containing directory in the zip archive itself, then you should call the AddDirectory() overload that allows you to explicitly specify a directory path for use in the archive.

For ZipFile properties including Encryption, , SetCompression, , ExtractExistingFile, ZipErrorAction, and CompressionLevel, their respective values at the time of this call will be applied to each ZipEntry added.

public AddDirectory ( string directoryName ) : ZipEntry
directoryName string The name of the directory to add.
return ZipEntry
示例#1
0
 /// <summary>
 /// 压缩ZIP文件
 /// </summary>
 /// <param name="fileList">待压缩的文件或目录集合</param>
 /// <param name="zipName">压缩后的文件名</param>
 /// <param name="isDirStruct">是否按目录结构压缩</param>
 public static bool Compress(List<string> fileList, string zipName, bool isDirStruct)
 {
     try
     {
         using (var zip = new ZipFile(Encoding.Default))
         {
             foreach (string path in fileList)
             {
                 string fileName = Path.GetFileName(path);
                 if (Directory.Exists(path))
                 {
                     //按目录结构压缩
                     if (isDirStruct)
                     {
                         zip.AddDirectory(path, fileName);
                     }
                     else//目录下文件压缩到根目录
                     {
                         zip.AddDirectory(path);
                     }
                 }
                 if (File.Exists(path))
                 {
                     zip.AddFile(path);
                 }
             }
             zip.Save(zipName);
             return true;
         }
     }
     catch (Exception)
     {
         return false;
     }
 }
示例#2
0
        public void Archive(string rootPath, string archiveFilename, CancellationToken cancellationToken, SimpleProgressCallback progressCallback = null)
        {
            using (ZipFile file = new ZipFile(archiveFilename))
            {
                // add all the files from the report to the zip file
                file.AddDirectory(rootPath);

                // subscribe for the archiving progress event
                file.SaveProgress += (sender, args) =>
                                         {
                                             // check if the cancellation was requested
                                             if (cancellationToken.IsCancellationRequested)
                                             {
                                                 args.Cancel = true;
                                                 return;
                                             }

                                             if (args.EntriesTotal == 0)
                                             {
                                                 // avoid division by zero
                                                 return;
                                             }

                                             progressCallback.TryInvoke((args.EntriesSaved + (args.TotalBytesToTransfer > 0 ? 1.0 * args.BytesTransferred / args.TotalBytesToTransfer : 0.0)) / args.EntriesTotal);
                                         };

                // safe file to disk
                file.Save();

                cancellationToken.ThrowIfCancellationRequested();
            }

            // report operation finished
            progressCallback.TryInvoke(1.0);
        }
示例#3
0
 /// <summary>
 /// ZIP komprimiert den Inhalt des übergebenen Verzeichnisses in die übergebene Datei.
 /// </summary>
 /// <param name="directory"></param>
 /// <param name="targetFilePath"></param>
 public void CompressDirContentTo(string directory, string targetFilePath)
 {
     using (var zip = new Ionic.Zip.ZipFile()) {
         zip.AddDirectory(directory, "");
         zip.Save(targetFilePath);
     }
 }
示例#4
0
        /// <summary>
        /// Create a self-extracting ZIP using the DoNetZip library
        /// </summary>
        public static void CreateSelfExtractingZip(string outputFile, string tempFilePath, string productVersion, string productDescription, string installPath, string postExtractCommand)
        {
            if (!String.IsNullOrEmpty(outputFile))
            {
                using (var zip = new ZipFile())
                {
                    zip.AddDirectory(tempFilePath);

                    var options = new SelfExtractorSaveOptions
                    {
                        ProductName = productDescription,
                        ProductVersion = productVersion,
                        FileVersion = new System.Version(productVersion),
                        Description = productDescription,
                        Copyright = "Copyright © Influence Health 2015",
                        DefaultExtractDirectory = installPath,
                        Flavor = SelfExtractorFlavor.WinFormsApplication,
                        Quiet = false,
                        RemoveUnpackedFilesAfterExecute = false,
                        IconFile = Environment.CurrentDirectory + @"\Installer.ico",
                        ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently,
                        PostExtractCommandLine = postExtractCommand
                    };
                    zip.SaveSelfExtractor(outputFile, options);
                }
            }
        }
示例#5
0
        public static void ZipDirectory(string dir)
        {
            string zipfile_name = dir + ".zip";
            if (File.Exists(zipfile_name))
            {
                return;
            }

            using (var zip = new ZipFile(Encoding.GetEncoding("shift_jis")))
            {
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;

                var di = new DirectoryInfo(dir);

                foreach (var i in di.EnumerateFileSystemInfos())
                {
                    if (FileAttributes.Directory == (i.Attributes & FileAttributes.Directory))
                    {
                        zip.AddDirectory(i.FullName, i.Name);
                    }
                    else if (FileAttributes.Hidden != (i.Attributes & FileAttributes.Hidden))
                    {
                        zip.AddFile(i.FullName, "");
                    }
                }

                zip.Save(zipfile_name);
            }
        }
示例#6
0
        public static void ZipFiles(string zipFile, string rootPath, string[] files)
        {
			using (ZipFile zip = new ZipFile())
			{
				//use unicode if necessary
				zip.UseUnicodeAsNecessary = true;
				//skip locked files
				zip.ZipErrorAction = ZipErrorAction.Skip;
				foreach (string file in files)
				{
					string fullPath = Path.Combine(rootPath, file);
					if (Directory.Exists(fullPath))
					{
						//add directory with the same directory name
						zip.AddDirectory(fullPath, file);
					}
					else if (File.Exists(fullPath))
					{
						//add file to the root folder
						zip.AddFile(fullPath, "");
					}
				}
				zip.Save(zipFile);
			}
        }
示例#7
0
        /// <summary>
        /// 压缩zip
        /// </summary>
        /// <param name="fileToZips">文件路径集合</param>
        /// <param name="zipedFile">想要压成zip的文件名</param>
        public static void ZipOld(string[] fileToZips, string zipedFile)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipedFile, Encoding.UTF8))
            {
                List <string> pathlist = new List <string>();
                foreach (string fileToZip in fileToZips)
                {
                    if (System.IO.File.Exists(fileToZip))
                    {
                        using (FileStream fs = new FileStream(fileToZip, FileMode.Open, FileAccess.Read))
                        {
                            byte[] buffer = new byte[fs.Length];
                            fs.Read(buffer, 0, buffer.Length);
                            string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1);
                            string filePath = fileToZip.Substring(0, fileToZip.LastIndexOf("\\"));

                            if (!pathlist.Exists(x => x.Equals(filePath)))
                            {
                                pathlist.Add(filePath);
                                zip.AddDirectoryByName(filePath);
                            }
                            zip.AddFile(fileToZip, filePath);
                        }
                    }
                    if (System.IO.Directory.Exists(fileToZip))
                    {
                        string filePath = fileToZip.Substring(fileToZip.IndexOf("\\") + 1);
                        zip.AddDirectoryByName(filePath);
                        zip.AddDirectory(fileToZip, filePath);
                        //ZipFileDictory(fileToZip, "", zip);
                    }
                }
                zip.Save();
            }
        }
示例#8
0
    private static void CollectLogFiles(string dataPath, string outputPath, List<string> products)
    {
      if (!Directory.Exists(outputPath))
        Directory.CreateDirectory(outputPath);

      string targetFile = string.Format("MediaPortal2-Logs-{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HH.mm.ss"));
      targetFile = Path.Combine(outputPath, targetFile);
      if (File.Exists(targetFile))
        File.Delete(targetFile);

      ZipFile archive = new ZipFile(targetFile);
      foreach (var product in products)
      {
        string sourceFolder = Path.Combine(dataPath, @"Team MediaPortal", product, "Log");
        if (!Directory.Exists(sourceFolder))
        {
          Console.WriteLine("Skipping non-existant folder {0}", sourceFolder);
          continue;
        }
        Console.WriteLine("Adding folder {0}", sourceFolder);
        try
        {
          archive.AddDirectory(sourceFolder, product);
        }
        catch (Exception ex)
        {
          Console.WriteLine("Error adding folder {0}: {1}", sourceFolder, ex);
        }
      }
      archive.Save();
      archive.Dispose();
      Console.WriteLine("Successful created log archive: {0}", targetFile);

      Process.Start(outputPath); // Opens output folder
    }
示例#9
0
        public void Run(string containerName)
        {
            if (!this.folderConnection.IsValid())
            {
                throw new DirectoryNotFoundException(string.Format("Unable to access {0}", this.folderConnection.Path));
            }

            List<string> containers = this.cloudConnection.GetContainers();

            if (containers.IsNullOrEmpty() || !containers.Contains(containerName))
            {
                throw new IndexOutOfRangeException(string.Format("Could not find Container: {0}", containerName));
            }

            using (var stream = new MemoryStream())
            {
                using (var zipFile = new ZipFile())
                {
                    zipFile.AddDirectory(this.folderConnection.Path);
                    zipFile.Save(stream);

                    stream.Seek(0, SeekOrigin.Begin);
                    this.cloudConnection.PutStorageItem(containerName, stream, this.folderConnection.ZipName);
                }
            }
        }
示例#10
0
        private void Folder_zip_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtfolder.Text))
            {
                MessageBox.Show("Please select a proper folder", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtfolder.Focus();
                return;
            }
            string path   = txtfolder.Text;
            Thread thread = new Thread(t =>
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    zip.AddDirectory(path);
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path);
                    zip.SaveProgress          += Zip_SaveProgress;
                    zip.Save(string.Format("{0}{1}.zip", di.Parent.FullName, di.Name));
                }
            })
            {
                IsBackground = true
            };

            thread.Start();
        }
示例#11
0
        protected override Task<HttpResponseMessage> CreateDirectoryGetResponse(DirectoryInfo info, string localFilePath)
        {
            HttpResponseMessage response = Request.CreateResponse();
            using (var zip = new ZipFile())
            {
                foreach (FileSystemInfo fileSysInfo in info.EnumerateFileSystemInfos())
                {
                    bool isDirectory = (fileSysInfo.Attributes & FileAttributes.Directory) != 0;

                    if (isDirectory)
                    {
                        zip.AddDirectory(fileSysInfo.FullName, fileSysInfo.Name);
                    }
                    else
                    {
                        // Add it at the root of the zip
                        zip.AddFile(fileSysInfo.FullName, "/");
                    }
                }

                using (var ms = new MemoryStream())
                {
                    zip.Save(ms);
                    response.Content = ms.AsContent();
                }
            }

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

            // Name the zip after the folder. e.g. "c:\foo\bar\" --> "bar"
            response.Content.Headers.ContentDisposition.FileName = Path.GetFileName(Path.GetDirectoryName(localFilePath)) + ".zip";
            return Task.FromResult(response);
        }
示例#12
0
        private static void AddFolderToZip(ZipFile zipFile, string packageRootFolder, string addFolder)
        {
            string sourceFolder = Path.Combine(packageRootFolder, addFolder);

            if (Directory.Exists(sourceFolder))
                zipFile.AddDirectory(sourceFolder, addFolder);
        }
        public byte[] Create(string templateZipFileName, string projectName)
        {
            var temporaryZipFilePath = CreateTemporaryZippedTemplate(templateZipFileName);
            var temporaryRenamingFolder = Path.Combine(_downloadFolder, Path.GetFileNameWithoutExtension(temporaryZipFilePath));

            using (var zipFile = ZipFile.Read(temporaryZipFilePath))
            {
                zipFile.ExtractAll(temporaryRenamingFolder);
            }

            File.Delete(temporaryZipFilePath);

            var renamer = new SolutionRenamer(temporaryRenamingFolder, templateZipFileName, projectName);
            renamer.Rename();

            using (var zipFile = new ZipFile())
            {
                zipFile.AddDirectory(Path.Combine(temporaryRenamingFolder, projectName));
                zipFile.Save(Path.Combine(_downloadFolder, Path.GetFileNameWithoutExtension(temporaryZipFilePath) + ".zip"));
            }

            Directory.Delete(temporaryRenamingFolder, true);

            var bytes = File.ReadAllBytes(temporaryZipFilePath);

            File.Delete(temporaryZipFilePath);

            return bytes;
        }
示例#14
0
 public void FolderToZip(string sourceDir, string path)
 {
     using (var surveyBackup = new ZipFile()) {
         surveyBackup.AddDirectory(sourceDir);
         surveyBackup.Save(path);
     }
 }
示例#15
0
        public HttpResponseMessage GetDiagnostics()
        {
            lock (_lockObj)
            {
                var response = new HttpResponseMessage();
                using (var zip = new ZipFile())
                {
                    foreach (var path in _paths)
                    {
                        if (Directory.Exists(path))
                        {
                            zip.AddDirectory(path, Path.GetFileName(path));
                        }
                    }

                    var ms = new MemoryStream();
                    zip.Save(ms);
                    response.Content = ms.AsContent();
                }
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = String.Format("dump-{0:MM-dd-H:mm:ss}.zip", DateTime.UtcNow);
                return response;
            }
        }
		private void SaveButton_Click(object sender, EventArgs e)
		{
			SaveFileDialog Dialog = new SaveFileDialog();
			Dialog.Filter = "Zip Files (*.zip)|*.zip|AllFiles (*.*)|*.*";
			Dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
			Dialog.FileName = Path.Combine(Dialog.InitialDirectory, "UGS-Diagnostics.zip");
			if(Dialog.ShowDialog() == DialogResult.OK)
			{
				string DiagnosticsFileName = Path.Combine(DataFolder, "Diagnostics.txt");
				try
				{
					File.WriteAllLines(DiagnosticsFileName, DiagnosticsTextBox.Lines);
				}
				catch(Exception Ex)
				{
					MessageBox.Show(String.Format("Couldn't write to '{0}'\n\n{1}", DiagnosticsFileName, Ex.ToString()));
					return;
				}

				string ZipFileName = Dialog.FileName;
				try
				{
					ZipFile Zip = new ZipFile();
					Zip.AddDirectory(DataFolder);
					Zip.Save(ZipFileName);
				}
				catch(Exception Ex)
				{
					MessageBox.Show(String.Format("Couldn't save '{0}'\n\n{1}", ZipFileName, Ex.ToString()));
					return;
				}
			}
		}
示例#17
0
 private void createSelfExtractingZip(MyFile mf)
 {
     try {
         NetworkDrives.MapDrive("iboxx");                                                                          //comment for local testing 3/26
         using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) {
             if (mf.IsFolder)
             {
                 zip.AddDirectory(mf.From);
             }
             else
             {
                 zip.AddFile(mf.From);
             }
             Ionic.Zip.SelfExtractorSaveOptions options = new Ionic.Zip.SelfExtractorSaveOptions();
             options.Flavor = Ionic.Zip.SelfExtractorFlavor.ConsoleApplication;
             zip.SaveSelfExtractor(mf.FullName, options);
         }
         NetworkDrives.DisconnectDrive("iboxx");                                                                   //comment for local testing
     } catch (Exception e) {
         displayError(e);
         throw;
         //if (Error == "") {
         //    Error = "Error caught in createSelfExtractingZip() " + e;
         //    throw;
         //}
         ////ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "Message", "<script>alert('Error caught in createSelfExtractingZip() " + e + "');</script>", true);
         ////this.Response.Write("<script>alert('Error caught in createSelfExtractingZip() " + e + "');</script>");
     }
 }
示例#18
0
 public static String extractIPA(IPAInfo info)
 {
     using (ZipFile ipa = ZipFile.Read(info.Location))
     {
         Debug("IPALocation: " + info.Location);
         Debug("Payload location: " + info.BinaryLocation);
         foreach (ZipEntry e in ipa)
         {
             //Debug ("file:" + e.FileName);
             if (e.FileName.Contains(".sinf") || e.FileName.Contains(".supp"))
             {
                 //extract it
                 Debug(GetTemporaryDirectory());
                 e.Extract(GetTemporaryDirectory(), ExtractExistingFileAction.OverwriteSilently);
             }
             else if (e.FileName == info.BinaryLocation)
             {
                 Debug("found binary!!");
                 e.Extract(GetTemporaryDirectory(), ExtractExistingFileAction.OverwriteSilently);
             }
         }
     }
     //zip!
     String AppDirectory = Path.Combine(GetTemporaryDirectory(), "Payload");
     Debug("AppDirectory: " + AppDirectory);
     //return null;
     String ZipPath = Path.Combine(GetTemporaryDirectory(), "upload.ipa");
     using (ZipFile zip = new ZipFile())
     {
         zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
         zip.AddDirectory(AppDirectory);
         zip.Save(ZipPath);
     }
     return ZipPath;
 }
示例#19
0
        public static int Main(string[] args)
        {
            var options = new Options();

            if (!ParseCommandLineOptions(args, options))
                return 1;

            if (options.OutputDir == null)
                options.OutputDir = options.PackageDir;

            if (!Directory.Exists(options.OutputDir))
                Directory.CreateDirectory(options.OutputDir);

            var packageDllName = options.PackageName + ".dll";
            var packageArchiveName = options.PackageName + ".0.0.0.fld";
            var packageDllPath = Path.Combine(options.PackageDir, packageDllName);
            var packageArchivePath = Path.Combine(options.OutputDir, packageArchiveName);

            //Generate RPC classes
            if (!RemotingGen.Program.Generate(packageDllPath, options.PackageDir, false))
                return 1;

            //Create an archive
            using (var zip = new ZipFile())
            {
                zip.AddDirectory(options.PackageDir, "");
                zip.Save(packageArchivePath);
            }

            return 0;
        }
示例#20
0
        internal static void CreateZipFile(this SolutionInfo si)
        {
            using (var zip = new ZipFile())
            {
                zip.AddDirectory(si.TempPath);
                var zipDirectory = Program.Options.ZipDirectory;

                // No ZipDirectory provided
                if (string.IsNullOrWhiteSpace(zipDirectory))
                {
                    // Default to the parent folder of the solution
                    zipDirectory = Path.GetFullPath(Path.Combine(si.Directory, ".."));
                    if (!Directory.Exists(zipDirectory))
                    {
                        // No parent folder then use the solution directory
                        zipDirectory = si.Directory;
                    }
                }

                var zipName = Path.Combine(zipDirectory, si.Name + ".zip");
                zip.Save(zipName);
                CommandLine.WriteLineColor(ConsoleColor.Yellow, "Created zip file {0}", zipName);
                si.TempPath.Delete();
            }
        }
示例#21
0
        public static void DoubleZipFileContent(string folderSource, string fileDest, string password)
        {
            using (var zip = new ZipFile())
            {
                zip.AlternateEncoding = Encoding.UTF8;
                zip.AlternateEncodingUsage = ZipOption.Always;

                zip.Password = password;
                zip.Encryption = EncryptionAlgorithm.WinZipAes128;
                zip.AddDirectory(folderSource);
                zip.Save(Path.Combine(folderSource, "content.zip"));
            }

            using (var doubleZip = new ZipFile())
            {
                doubleZip.AlternateEncoding = Encoding.UTF8;
                doubleZip.AlternateEncodingUsage = ZipOption.Always;

                doubleZip.Password = password;
                doubleZip.Encryption = EncryptionAlgorithm.WinZipAes128;
                doubleZip.AddFile(Path.Combine(folderSource, "content.zip"), "");
                doubleZip.Save(fileDest);
            }

            if (File.Exists(Path.Combine(folderSource, "content.zip")))
                File.Delete(Path.Combine(folderSource, "content.zip"));
        }
示例#22
0
        public FileResult GetPages()
        {
            if (Request.Url != null)
            {
                var zip = new ZipFile();
                zip.AddDirectoryByName("Content");
                zip.AddDirectory(Server.MapPath("~/Content/"), "Content");
                var paths = DtoHelper.GetPaths();
                foreach (var path in paths)
                {
                    var url = Url.Action(path.Action, path.Controller, null, Request.Url.Scheme);
                    if (url != null)
                    {
                        var request = WebRequest.Create(string.Concat(url, Constants.Resources.DownloadParameter));
                        request.Credentials = CredentialCache.DefaultCredentials;
                        var response = (HttpWebResponse)request.GetResponse();
                        var dataStream = response.GetResponseStream();
                        {
                            if (dataStream != null)
                            {
                                zip.AddEntry(path.FileName, dataStream);
                            }
                        }
                    }
                }
                var stream = new MemoryStream();
                zip.Save(stream);
                stream.Position = 0;
                return new FileStreamResult(stream, "application/zip") { FileDownloadName = Constants.Resources.DownloadName };

            }
            return null;
        }
示例#23
0
            static void Main(string[] args) {
               
               string ZipFilePath = Path.Combine("", "TestArchive.zip");
               if (File.Exists(ZipFilePath)) File.Delete(ZipFilePath);
                var zip = new ZipFile(ZipFilePath);
                zip.AddDirectory("LocalVFS", "LocalVFS/");
                zip.Save();
                zip.Dispose();
                //
                ZipFileSystemConfiguration zc = ZipFileSystemConfiguration.CreateDefaultConfig(ZipFilePath,"_tmp_");
                ZipFileProvider lp = new ZipFileProvider(zc);
                bool exfd = lp.ExistFolder("LocalVFS/", true);
                if (exfd) {
                    lp.DeleteFolder("LocalVFS/");
                }
                byte[] dataTest = Encoding.UTF8.GetBytes("this is a test context!!!");
                File.WriteAllBytes("test.cs", dataTest);
                lp.CreateFolder("LocalVFS/");
                string filepath = lp.CreateFilePath("LocalVFS/", "test.txt");

                //lp.MoveFile("test.cs", filepath);
                byte[] dataTest2 = Encoding.UTF8.GetBytes("this is a test write data!!!");
                using (MemoryStream ms = new MemoryStream(dataTest2)) {
                    lp.WriteFile("LocalVFS/test.txt", ms, true, dataTest2.Length, ContentUtil.UnknownContentType);
                }
                //lp.DeleteFile("LocalVFS/test.txt");
                lp.CopyFolder("LocalVFS/", "localvfs_test/");
                lp.Dispose();
                int jj = 0;
            }
示例#24
0
 public static void BuildPackage(IEnumerable<string> includes, string outputFileName)
 {
     File.Delete(outputFileName);
     using (var zipFile = new ZipFile(outputFileName))
     {
         foreach (var include in includes)
         {
             if (include.Length < 3)
             {
                 throw new PackManException("Include option must have following format: f|d|p:<value>.");
             }
             char type = char.ToLower(include[0]);
             string value = include.Substring(2);
             switch (type)
             {
                 case 'f':
                     zipFile.AddFile(value);
                     break;
                 case 'd':
                     zipFile.AddDirectory(value);
                     break;
                 case 'p':
                     zipFile.AddSelectedFiles(value,true);
                     break;
             }
         }
         zipFile.Save();
     }
 }
        public string CreateSolution(IBuildBootstrappedSolutions bootstrapper, SolutionConfiguration configuration)
        {
            configuration.InCodeSubscriptions = true;
            foreach (var endpointConfiguration in configuration.EndpointConfigurations)
            {
                endpointConfiguration.InCodeSubscriptions = configuration.InCodeSubscriptions;
            }

            var solutionData = bootstrapper.BootstrapSolution(configuration);

            var solutionDirectory = SavePath + Guid.NewGuid();

            var solutionFile = SaveSolution(solutionDirectory, solutionData);

            InstallNuGetPackages(solutionDirectory, solutionData, solutionFile, NuGetExe);

            //AddReferencesToNugetPackages(solutionDirectory);

            var zipFilePath = solutionFile.Replace(".sln", ".zip");

            using (var zip = new ZipFile())
            {
                zip.AddDirectory(solutionDirectory, "Solution");
                zip.Save(zipFilePath);
            }

            return zipFilePath;
        }
示例#26
0
        public static void DoCopy()
        {
            using (var stream = new StreamReader(@"C:\CopyItems.xml"))
            {
                var deserializer = new XmlSerializer(typeof(List<CopyItem>));

                var items = (List<CopyItem>)deserializer.Deserialize(stream);
                log.Info($"Zdeserializowano elementy: liczba {items.Count}");

                foreach (var item in items)
                {
                    string date = DateTime.Now.ToShortDateString();

                    string mainDirPath = Path.Combine(item.Target, item.Name, date);
                    if (!Directory.Exists(mainDirPath))
                    {
                        Directory.CreateDirectory(mainDirPath);
                    }

                    using (ZipFile zip = new ZipFile())
                    {
                        zip.AddDirectory(item.Source);
                        
                        string path = Path.Combine(mainDirPath, Path.GetFileName(item.Source) + ".zip");

                        zip.Save(path);
                    }
                }
            }
        }
示例#27
0
        public MemoryStream Zip(InputConfiguration inputConfig)
        {
            var stream = new MemoryStream();
            using (var zip = new ZipFile())
            {
                SetCompressionLevel(zip, 0);
                CreateFolders(zip, inputConfig.HasView);
                AddInputConfig(zip, inputConfig);
                AddMediaFiles(zip, inputConfig);
                foreach (var inputAction in inputConfig.Actions)
                {
                    if (!inputAction.HasScriptSequences)
                        continue;
                    AddScripts(zip, inputAction);
                }
                if (inputConfig.HasView)
                {
                    var path = Path.Combine(appConfigProvider.AppConfig.ViewsRoot, inputConfig.View);
                    if (new FileSystemUtils().DirectoryExists(path))
                        zip.AddDirectory(path, "Views\\" + inputConfig.View);
                }

                stream.Seek(0, SeekOrigin.Begin);
                zip.Save(stream);

            }
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }
示例#28
0
        public override void Execute(object parameter)
        {
            var active = MainViewModel.ActiveDirectoryContainer.ActiveView;
            var dialog = new CompressDialog();
            if (dialog.ShowModalDialog())
            {
                using (var zipFile = new ZipFile())
                {
                    foreach (var item in MainViewModel.GetSelectedItems())
                    {
                        if (item.IsMoveUp)
                            continue;
                        else if (item.IsDirectory)
                            zipFile.AddDirectory(item.FullName);
                        else
                            zipFile.AddFile(item.FullName);
                    }

                    if (!string.IsNullOrEmpty(dialog.Password))
                    {
                        zipFile.Password = dialog.Password;
                        zipFile.Encryption = EncryptionAlgorithm.WinZipAes256;
                    }

                    zipFile.Save(Path.Combine(active.FullPath, dialog.FileName));
                }
            }
        }
示例#29
0
 public static void ZipDirectory(string dirOnDisk, string dirPathInArchive, string zipPath)
 {
     using (var zip = new Ionic.Zip.ZipFile())
     {
         zip.AddDirectory(dirOnDisk, dirPathInArchive);
         zip.Save(zipPath);
     }
 }
示例#30
0
 public static void CreateFromDirectory(string directory, string targetZip)
 {
     using (var zip = new Ionic.Zip.ZipFile())
     {
         zip.AddDirectory(directory);
         zip.Save(targetZip);
     }
 }
示例#31
0
 public static void zip(string directory, string zipFileName)
 {
     Console.WriteLine("Zipping '{0}' to '{1}'", directory, zipFileName);
     using (var zip = new ZipFile()) {
         zip.AddDirectory(directory);
         zip.Save(zipFileName);
     }
 }
示例#32
0
 /// <summary>
 /// 压缩目录
 /// </summary>
 /// <param name="source">要压缩的目录</param>
 /// <param name="descZip">压缩后的文件名</param>
 /// <param name="password">密码</param>
 public void Directory(string source, string descZip, string password = null) {
     source = source.Trim('\\') + "\\";
     using (ZipFile zip = new ZipFile()) {
         if (!password.IsNullEmpty()) zip.Password = password;
         zip.AddDirectory(source, "");
         zip.Save(descZip);
     }
 }
示例#33
0
 private static void zip(string dir, string dest, string folderName)
 {
     using (ZipFile zip = new ZipFile())
     {
         zip.AddDirectory(dir, folderName);
         zip.Save(dest);
     }
 }
 public static void Zip(string Folder, string ZipFile)
 {
     using (Ionic.Zip.ZipFile zipFiles = new Ionic.Zip.ZipFile())
     {
         zipFiles.AddDirectory(Folder);
         zipFiles.Save(ZipFile);
     }
 }
示例#35
0
 public static void CreateFromDirectory(string sourceFolder, string archiveFileName)
 {
     using (var zipFile = new Ionic.Zip.ZipFile(Encoding.UTF8))
     {
         zipFile.AddDirectory(sourceFolder);
         zipFile.Save(archiveFileName);
     }
 }
示例#36
0
 public static void CreateFromDirectory(string directory, string targetZip)
 {
     using (var zip = new Ionic.Zip.ZipFile())
     {
         zip.AddDirectory(directory);
         zip.Save(targetZip);
     }
 }
示例#37
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 void RezipCase(string path)
 {
     using (ZipFile zip = new ZipFile())
     {
         zip.AddDirectory(path, Path.GetFileName(path));
         zip.Save(Path.Combine(Directory.GetParent(path).FullName, Path.GetFileName(path) + Constants.ContainerExtension));
     }
     OsirtHelper.DeleteDirectory(path);
 }
示例#39
0
 public static void CreateFromDirectory(string directory, string targetZip)
 {
     using (var zip = new Ionic.Zip.ZipFile())
     {
         zip.UseZip64WhenSaving = Zip64Option.AsNecessary;
         zip.AddDirectory(directory);
         zip.Save(targetZip);
     }
 }
示例#40
0
 public static void CompressDir(string dirctoryname, string save, Encoding encoding = default(Encoding))
 {
     if (encoding == default(Encoding))
     {
         encoding = Encoding.Default;
     }
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(encoding))
     {
         zip.AddDirectory(dirctoryname);
         zip.Save(save);
     }
 }
示例#41
0
        public static void Compress(string zipFilePath, string sourceDirPath, string password)
        {
            using (var zipFile = new ZipFileManager(SharedObjects.Encodings.ShiftJis))
            {
                if (password != null)
                {
                    zipFile.Password = password;
                }

                zipFile.AddDirectory(sourceDirPath);
                zipFile.Save(zipFilePath);
            }
        }
示例#42
0
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="dir">文件夹目录</param>
        /// <param name="encoding">编码</param>
        /// <returns></returns>
        public static Stream CompressDirOutStream(string dir, Encoding encoding = default(Encoding))
        {
            if (encoding == default(Encoding))
            {
                encoding = Encoding.Default;
            }
            MemoryStream stream = new MemoryStream();

            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(encoding))
            {
                zip.AddDirectory(dir);
                zip.Save(stream);
                stream.Position = 0;
            }
            return(stream);
        }
示例#43
0
        public string comprimir_Carpetas_ant(string nombreFile)
        {
            string resultado = "";

            try
            {
                string ruta_origen  = ConfigurationManager.AppSettings["ruta_origen"];
                string ruta_destino = ConfigurationManager.AppSettings["ruta_destino"] + "julio.zip";

                List <string> items = new List <string>();
                items.Add(ruta_origen + "Juliodoc");   //---carpeta
                items.Add(ruta_origen + "chokis.jpg"); //---- archivos normales

                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    foreach (string item in items)
                    {
                        if (System.IO.File.Exists(item))
                        {
                            //agregando un archivo normal
                            zip.AddFile(item, "");
                        }   // if the item is a folder
                        else if (System.IO.Directory.Exists(item))
                        {
                            // añadiendo una carpeta con todo sus sub directorios
                            zip.AddDirectory(item, new System.IO.DirectoryInfo(item).Name);
                        }
                    }
                    // Guardando el archivo zip
                    zip.Save(ruta_destino);
                }
                if (File.Exists(ruta_destino))
                {
                    resultado = "El proceso finalizo.";
                }
                else
                {
                    resultado = "No se genero";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(resultado);
        }
示例#44
0
 //create backup button click event
 private void createBkupBtn_Click(object sender, RoutedEventArgs e)
 {
     if (directoryBox.Text != "")
     {
         using (var zip = new Ionic.Zip.ZipFile())
         {
             //select the path to zip
             zip.AddDirectory(GlobalVariables.appDirectoryPath);
             //save the ziped file
             zip.Save(directoryBox.Text + @"\BackUp.zip");
         }
     }
     else
     {
         MessageBox.Show("Select a directory first");
     }
 }
示例#45
0
        public string comprimir_Carpetas(List <download> list_download, int usuario_creacion)
        {
            string resultado = "";

            try
            {
                string ruta_destino  = System.Web.Hosting.HostingEnvironment.MapPath("~/Documentos/Descargas/" + usuario_creacion + "_Descarga.zip");
                string ruta_descarga = ConfigurationManager.AppSettings["servidor_files"] + "Descargas/" + usuario_creacion + "_Descarga.zip";

                if (File.Exists(ruta_destino)) //--- restaurarlo
                {
                    System.IO.File.Delete(ruta_destino);
                }
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    foreach (download item in list_download)
                    {
                        if (System.IO.File.Exists(item.ubicacion))
                        {
                            //agregando un archivo normal
                            zip.AddFile(item.ubicacion, "");
                        }   // if the item is a folder
                        else if (System.IO.Directory.Exists(item.ubicacion))
                        {
                            zip.AddDirectory(item.ubicacion, new System.IO.DirectoryInfo(item.ubicacion).Name);
                        }
                    }
                    // Guardando el archivo zip
                    zip.Save(ruta_destino);
                }
                if (File.Exists(ruta_destino))
                {
                    resultado = ruta_descarga;
                }
                else
                {
                    throw new System.InvalidOperationException("No se pudo generar la Descarga del Archivo");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(resultado);
        }
示例#46
0
 /// <summary>
 /// Compacta uma lista de arquivo em um arquivo .zip
 /// </summary>
 /// <param name="files"></param>Arquivos
 /// <param name="zipOut"></param>Arquivo .zip de saida
 /// <returns></returns>true compactado ou false erro
 public static void CompressFileList(List <string> files, string zipOut)
 {
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
     {
         // percorre todos os arquivos da lista
         foreach (string item in files)
         {
             // se o item é um arquivo
             if (File.Exists(item))
             {
                 try
                 {
                     // Adiciona o arquivo na pasta raiz dentro do arquivo zip
                     zip.AddFile(item, "");
                 }
                 catch (Exception ex)
                 {
                     throw ex;
                 }
             }
             // se o item é uma pasta
             else if (Directory.Exists(item))
             {
                 try
                 {
                     // Adiciona a pasta no arquivo zip com o nome da pasta
                     zip.AddDirectory(item, new DirectoryInfo(item).Name);
                 }
                 catch
                 {
                     throw;
                 }
             }
         }
         // Salva o arquivo zip para o destino
         try
         {
             zip.Save(zipOut);
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }
 }
    static public Boolean ComprimirFolder(string Ruta, string Nombre)
    {
        try
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                zip.AddDirectory(Ruta);
                String Rut = HttpContext.Current.Server.MapPath("Comprimidos/" + Nombre);
                zip.Save(Rut);
            }

            return(true);
        }
        catch (Exception ex)
        {
            return(false);
        }
    }
示例#48
0
        public override void Build()
        {
            UpdateNlib();
            string outp = BuildPath + "main.js";

            File.Delete(outp);
            foreach (var library in Libraries)
            {
                string text = library.GetCode();
                File.AppendAllText(outp, "\n" + text, ProgramData.Encoding);
            }
            foreach (var file in Directory.GetFiles(ScriptsPath))
            {
                string text = File.ReadAllText(file, ProgramData.Encoding);
                File.AppendAllText(outp, "\n" + text, ProgramData.Encoding);
            }
            if (Compress)
            {
                JavaScriptCompressor compressor = new JavaScriptCompressor();
                File.WriteAllText(outp, compressor.Compress(File.ReadAllText(outp, ProgramData.Encoding)), ProgramData.Encoding);
            }

            foreach (var file in OutFiles)
            {
                File.Copy(file, BuildPath + System.IO.Path.GetFileName(file), true);
                File.Copy(file, OutPath + System.IO.Path.GetFileName(file), true);
            }

            using (var zip = new Ionic.Zip.ZipFile())
            {
                zip.AddDirectoryByName("images");
                zip.AddDirectory(ResPath, "images");
                zip.Save(BuildPath + "resources.zip");
            }

            using (var zip = new Ionic.Zip.ZipFile())
            {
                zip.AddDirectoryByName("script");
                zip.AddFile(outp, "script");
                zip.AddDirectoryByName("images");
                zip.AddDirectory(ResPath, "images");
                zip.Save(OutPath + Name + ".modpkg");
            }
        }
示例#49
0
    public static void BuildServer()
    {
        // Get filename.
        string path = "./Build/Server";

        string[] levels = new string[] { "Assets/main.unity" };

        BuildPipeline.BuildPlayer(levels, path + "/gdwc.x86_64", BuildTarget.StandaloneLinux64, BuildOptions.EnableHeadlessMode);

        using (var zip = new Ionic.Zip.ZipFile()) {
            if (File.Exists("./Build/Server/gdwc.zip"))
            {
                File.Delete("./Build/Server/gdwc.zip");
            }
            zip.AddDirectory("./Build/Server");
            zip.Save("./Build/Server/gdwc.zip");
        }
        Debug.Log("Build done");
    }
示例#50
0
        void Worker_doWork(object sender, DoWorkEventArgs e)
        {
            String FileName = (String)e.Argument;

            using (Zip.ZipFile zip = new Zip.ZipFile())
            {
                zip.UseUnicodeAsNecessary = true;
                if (this.ArchivePassword != "")
                {
                    zip.Password = this.ArchivePassword;
                }
                zip.AddDirectory(this.DataBasePath);
                zip.SaveProgress += Zip_SaveProgress;

                //FileName = "Backup_" + System.DateTime.Now.ToString("dd_MM_yyyy") + ".zip";
                zip.Save(this.BackupPath + "\\" + FileName);
            }
            e.Result = FileName;
        }
示例#51
0
        private void kryptonButton2_Click(object sender, EventArgs e)
        {
            if (repcount.Text != "0")
            {
                // Show the FolderBrowserDialog.
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Archive Zip|*.Zip";
                saveFileDialog1.Title  = "Save Zip File To";
                saveFileDialog1.ShowDialog();

                // If the file name is not an empty string open it for saving.
                if (saveFileDialog1.FileName != "")
                {
                    backgroundWorker2.RunWorkerAsync();


                    String DirectoryToZip  = _recpacker;
                    String ZipFileToCreate = saveFileDialog1.FileName;

                    using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                    {
                        zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default;
                        zip.SaveProgress    += SaveProgress;

                        zip.StatusMessageTextWriter = System.Console.Out;
                        zip.AddDirectory(DirectoryToZip); // recurses subdirectories
                        zip.Save(ZipFileToCreate);
                    }

                    FileInfo sizez = new FileInfo(saveFileDialog1.FileName);
                    KryptonMessageBox.Show("ReplayPack Size: " + FormatByteSize(sizez.Length), "Success");
                }
                else
                {
                }
                //compression
            }
            else
            {
                KryptonMessageBox.Show("Add Recorded Games First!", "Dad Gum!");
            }
        }
示例#52
0
        /// <summary>
        /// 压缩zip
        /// </summary>
        /// <param name="fileToZips">文件路径集合</param>
        /// <param name="zipedFile">想要压成zip的文件名</param>
        public static void Zip(string[] fileToZips, string zipedFile, string basePath)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipedFile, Encoding.UTF8))
            {
                foreach (string fileToZip in fileToZips)
                {
                    if (System.IO.File.Exists(fileToZip))
                    {
                        zip.AddFile(fileToZip, fileToZip.Substring(basePath.Length, fileToZip.LastIndexOf('\\') - basePath.Length));
                        continue;
                    }

                    if (System.IO.Directory.Exists(fileToZip))
                    {
                        zip.AddDirectory(fileToZip, fileToZip.Substring(basePath.Length));
                    }
                }
                zip.Save();
            }
        }
示例#53
0
    public void ZipIPSW()
    {
        //get desktop folder
        object obj = null;

        obj     = Interaction.CreateObject("WScript.Shell");
        iDevice = iDevice.Replace(" ", "_");

        string FileName = "iFaith_" + iDevice + "-" + xml_ios + "_signed.ipsw";

        //delete ipsw if already exists
        if (File_Exists(obj.SpecialFolders("desktop") + "\\" + FileName) == true)
        {
            File_Delete(obj.SpecialFolders("desktop") + "\\" + FileName);
        }
        using (Ionic.Zip.ZipFile zip1 = new Ionic.Zip.ZipFile()) {
            zip1.CompressionLevel = Ionic.Zlib.CompressionLevel.LEVEL0_NONE;
            zip1.AddDirectory(temppath + "\\IPSW\\");
            zip1.Save(obj.SpecialFolders("desktop") + "\\" + FileName);
        }
    }
示例#54
0
        /// <summary>
        /// Compacta uma lista de arquivo em um arquivo .zip
        /// </summary>
        /// <param name="files"></param>Arquivos
        /// <param name="zipOut"></param>Arquivo .zip de saida
        /// <returns></returns>true compactado ou false erro
        public static bool CompressFiles(string[] files, string zipOut)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                try
                {
                    // percorre todos os arquivos da lista
                    foreach (string f in files)
                    {
                        // se o item é um arquivo
                        if (File.Exists(f))
                        {
                            // Adiciona o arquivo na pasta raiz dentro do arquivo zip
                            zip.AddFile(f, "");
                        }
                        // se o item é uma pasta
                        else if (Directory.Exists(f))
                        {
                            // Adiciona a pasta no arquivo zip com o nome da pasta
                            zip.AddDirectory(f, new DirectoryInfo(f).Name);
                        }
                    }

                    // Salva o arquivo zip para o destino
                    zip.Save(zipOut);

                    //tudo certo
                    return(true);
                }
                catch (Exception ex)
                {
                    LoggerUtilIts.ShowExceptionLogs(ex);
                    XMessageIts.ExceptionJustMessage(ex, "Falha ao compactar o arquivo");
                    //deu merda
                    return(false);
                }
            }
        }
示例#55
0
        private void button1_Click(object sender, EventArgs e)
        {
            string rich              = richTextBox1.Text;
            string zipfile           = textBox1.Text + ".zip";
            FolderBrowserDialog fold = new FolderBrowserDialog();

            fold.ShowDialog();

            using (var zip = new Ionic.Zip.ZipFile())
            {
                if (richTextBox1.TextLength > 0)
                {
                    richTextBox1.SaveFile(fold.SelectedPath + @"\Readme.txt", RichTextBoxStreamType.PlainText);
                }

                zip.AddDirectory(fold.SelectedPath, textBox1.Text);

                zip.Save(zipfile);

                MessageBox.Show("Done!");
                File.Copy(zipfile, @"Ready-for-Upload\" + zipfile, true);
                File.Delete(zipfile);
            }
        }
示例#56
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="folder">Folder to Compress</param>
        /// <param name="archiveDest">Enter a name without extension</param>
        /// <param name="cplLvl">Niveau de compression 0/1/2</param>
        /// <returns></returns>
        public static bool CompressFolder(string folder, string archiveDest, int cplLvl)
        {
            if (!Directory.Exists(folder))
            {
                return(false);
            }

            string zipName = archiveDest + ".zip";

            // Verification
            if (File.Exists(zipName))
            {
                //var res = MessageBox.Show(", do you want to delete it or abort ?", "ok", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                ////var res = MB_Decision.Show("Zip File Exists for this game", "Alert", destination: zipName, buttons: MB_Decision.Mode.NoStop);
                ////if (res == MB_Decision.Result.Pass)
                ////{
                ////    //MessageBox.Show("Zip Compression Aborted", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                ////    return false;
                ////}
                ////else if (res == MB_Decision.Result.Trash)
                ////{
                ////    // Move to Recycle.Bin
                ////    try
                ////    {
                ////        FileSystem.DeleteDirectory(zipName, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                ////    }
                ////    catch (Exception e)
                ////    {
                ////        Debug.WriteLine(e.Message);
                ////    }
                ////}
            }


            while (true)
            {
                try
                {
                    // Get value from enum
                    CompressionLevel cpLvl = (CompressionLevel)cplLvl;
                    using (Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile())
                    {
                        zipFile.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                        //zipFile.BufferSize = 4096;
                        zipFile.AddDirectory(folder);
                        zipFile.AddProgress += addProgress;

                        zipFile.SaveProgress += SaveProgress;

                        BoxProgress      = new ProgressCompFolder();
                        BoxProgress.Text = "Compression Zip";

                        Task.Run(() => zipFile.Save(zipName));

                        BoxProgress.ShowDialog();
                    }

                    return(true);
                }
                catch (Exception e)
                {
                    Debug.WriteLine($"Erreur de compression {e.Message}");
                    var res = MessageBox.Show($"Erreur lors de la compression zip, merci de régler le problème et decliquer sur retry:\n{e}", "Erreur", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Exclamation);

                    // Exit if abort
                    if (res == DialogResult.Abort)
                    {
                        return(false);
                    }
                }
            }
        }
    /// <summary>
    /// Publish this SCORM package to a conformant zip file.
    /// </summary>
    void Publish()
    {
        string timeLimitAction = "";

        switch (PlayerPrefs.GetInt("Time_Limit_Action"))
        {
        case 0:
            timeLimitAction = "";
            break;

        case 1:
            timeLimitAction = "exit,message";
            break;

        case 2:
            timeLimitAction = "exit,no message";
            break;

        case 3:
            timeLimitAction = "continue,message";
            break;

        case 4:
            timeLimitAction = "continue,no message";
            break;
        }

        string timeLimit = SecondsToTimeInterval(ParseFloat(PlayerPrefs.GetString("Time_Limit_Secs")));

        string webplayer = PlayerPrefs.GetString("Course_Export");
        string tempdir   = System.IO.Path.GetTempPath() + System.IO.Path.GetRandomFileName();

        System.IO.Directory.CreateDirectory(tempdir);
        CopyFilesRecursively(new System.IO.DirectoryInfo(webplayer), new System.IO.DirectoryInfo(tempdir));
        string zipfile = EditorUtility.SaveFilePanel("Choose Output File", webplayer, PlayerPrefs.GetString("Course_Title"), "zip");

        if (zipfile != "")
        {
            if (File.Exists(zipfile))
            {
                File.Delete(zipfile);
            }

            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipfile);
            zip.AddDirectory(tempdir);

            zip.AddItem(Application.dataPath + "/SCORM/Plugins/2004");

            string manifest = "<?xml version=\"1.0\" standalone=\"no\" ?>\n" +
                              "<manifest identifier=\"" + PlayerPrefs.GetString("Manifest_Identifier") + "\" version=\"1\"\n" +
                              "\t\txmlns = \"http://www.imsglobal.org/xsd/imscp_v1p1\"\n" +
                              "\t\txmlns:adlcp = \"http://www.adlnet.org/xsd/adlcp_v1p3\"\n" +
                              "\t\txmlns:adlseq = \"http://www.adlnet.org/xsd/adlseq_v1p3\"\n" +
                              "\t\txmlns:adlnav = \"http://www.adlnet.org/xsd/adlnav_v1p3\"\n" +
                              "\t\txmlns:imsss = \"http://www.imsglobal.org/xsd/imsss\"\n" +
                              "\t\txmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n" +
                              "\t\txmlns:lom=\"http://ltsc.ieee.org/xsd/LOM\"\n" +
                              "\t\txsi:schemaLocation = \"http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd\n" +
                              "\t\t\thttp://www.adlnet.org/xsd/adlcp_v1p3 adlcp_v1p3.xsd\n" +
                              "\t\t\thttp://www.adlnet.org/xsd/adlseq_v1p3 adlseq_v1p3.xsd\n" +
                              "\t\t\thttp://www.adlnet.org/xsd/adlnav_v1p3 adlnav_v1p3.xsd\n" +
                              "\t\t\thttp://www.imsglobal.org/xsd/imsss imsss_v1p0.xsd\n" +
                              "\t\t\thttp://ltsc.ieee.org/xsd/LOM lom.xsd\" >\n" +
                              "<metadata>\n" +
                              "\t<schema>ADL SCORM</schema>\n" +
                              "\t<schemaversion>2004 4th Edition</schemaversion>\n" +
                              "<lom:lom>\n" +
                              "\t<lom:general>\n" +
                              "\t\t<lom:description>\n" +
                              "\t\t\t<lom:string language=\"en-US\">" + PlayerPrefs.GetString("Course_Description") + "</lom:string>\n" +
                              "\t\t</lom:description>\n" +
                              "\t</lom:general>\n" +
                              "\t</lom:lom>\n" +
                              "</metadata>\n" +
                              "<organizations default=\"B0\">\n" +
                              "\t<organization identifier=\"B0\" adlseq:objectivesGlobalToSystem=\"false\">\n" +
                              "\t\t<title>" + PlayerPrefs.GetString("Course_Title") + "</title>\n" +
                              "\t\t<item identifier=\"i1\" identifierref=\"r1\" isvisible=\"true\">\n" +
                              "\t\t\t<title>" + PlayerPrefs.GetString("SCO_Title") + "</title>\n" +
                              "\t\t\t<adlcp:timeLimitAction>" + timeLimitAction + "</adlcp:timeLimitAction>\n" +
                              "\t\t\t<adlcp:dataFromLMS>" + PlayerPrefs.GetString("Data_From_Lms") + "</adlcp:dataFromLMS> \n" +
                              "\t\t\t<adlcp:completionThreshold completedByMeasure = \"" + (System.Convert.ToBoolean(PlayerPrefs.GetInt("completedByMeasure"))).ToString().ToLower() + "\" minProgressMeasure= \"" + PlayerPrefs.GetFloat("minProgressMeasure") + "\" />\n" +
                              "\t\t\t<imsss:sequencing>\n" +
                              "\t\t\t<imsss:limitConditions attemptAbsoluteDurationLimit=\"" + timeLimit + "\"/>\n" +
                              "\t\t\t</imsss:sequencing>\n" +
                              "\t\t</item>\n" +
                              "\t</organization>\n" +
                              "</organizations>\n" +
                              "<resources>\n" +
                              "\t<resource identifier=\"r1\" type=\"webcontent\" adlcp:scormType=\"sco\" href=\"" + PlayerPrefs.GetString("Course_Export_Name") + ".html\">\n" +
                              "\t\t<file href=\"" + PlayerPrefs.GetString("Course_Export_Name") + ".html\" />\n" +
                              "\t\t<file href=\"scripts/scorm.js\" />\n" +
                              "\t\t<file href=\"scripts/ScormSimulator.js\" />\n" +
                              "\t\t<file href=\"" + PlayerPrefs.GetString("Course_Export_Name") + ".unity3d\" />\n" +
                              "\t</resource>\n" +
                              "</resources>\n" +
                              "</manifest>";

            zip.AddEntry("imsmanifest.xml", ".", System.Text.ASCIIEncoding.ASCII.GetBytes(manifest));

            zip.Save();
            EditorUtility.DisplayDialog("SCORM Package Published", "The SCORM Package has been published to " + zipfile, "OK");
        }
    }
示例#58
0
    void Publish()
    {
        string webplayer = PlayerPrefs.GetString("Course_Export");
        string tempdir   = System.IO.Path.GetTempPath() + System.IO.Path.GetRandomFileName();

        System.IO.Directory.CreateDirectory(tempdir);
        CopyFilesRecursively(new System.IO.DirectoryInfo(webplayer), new System.IO.DirectoryInfo(tempdir));
        string zipfile = EditorUtility.SaveFilePanel("Choose Output File", webplayer, PlayerPrefs.GetString("Course_Title"), "zip");

        if (zipfile != "")
        {
            if (File.Exists(zipfile))
            {
                File.Delete(zipfile);
            }

            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipfile);
            zip.AddDirectory(tempdir);

            if (PlayerPrefs.GetInt("SCORM_Version") < 3)
            {
                zip.AddItem(Application.dataPath + "/ADL SCORM/Plugins/2004");
                string manifest =
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                    "<!-- exported by Unity-SCORM Integration Toolkit Version 1.4 Beta-->" +
                    "<manifest xmlns=\"http://www.imsglobal.org/xsd/imscp_v1p1\" xmlns:imsmd=\"http://www.imsglobal.org/xsd/imsmd_v1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:adlcp=\"http://www.adlnet.org/xsd/adlcp_v1p3\" xmlns:imsss=\"http://www.imsglobal.org/xsd/imsss\" xmlns:adlseq=\"http://www.adlnet.org/xsd/adlseq_v1p3\" xmlns:adlnav=\"http://www.adlnet.org/xsd/adlnav_v1p3\" identifier=\"MANIFEST-AECEF15E-06B8-1FAB-5289-73A0B058E2DD\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd http://www.adlnet.org/xsd/adlcp_v1p3 adlcp_v1p3.xsd http://www.imsglobal.org/xsd/imsss imsss_v1p0.xsd http://www.adlnet.org/xsd/adlseq_v1p3 adlseq_v1p3.xsd http://www.adlnet.org/xsd/adlnav_v1p3 adlnav_v1p3.xsd\" version=\"1.3\">" +
                    "  <metadata>" +
                    "    <schema>ADL SCORM</schema>"
                    + ((PlayerPrefs.GetInt("SCORM_Version") == 0)?"    <schemaversion>2004 4th Edition</schemaversion>":"")
                    + ((PlayerPrefs.GetInt("SCORM_Version") == 1)?"    <schemaversion>2004 3rd Edition</schemaversion>":"")
                    + ((PlayerPrefs.GetInt("SCORM_Version") == 2)?"    <schemaversion>2004 CAM 1.3</schemaversion>":"")
                    +
                    "  </metadata>" +
                    "  <organizations default=\"ORG-8770D9D9-AD66-06BB-9A3D-E87784C697FF\">" +
                    "    <organization identifier=\"ORG-8770D9D9-AD66-06BB-9A3D-E87784C697FF\">" +
                    "      <title>" + PlayerPrefs.GetString("Course_Title") + "</title>" +
                    "      <item identifier=\"ITEM-79701DB3-F0AD-9426-8C43-819F3CB0EE6E\" identifierref=\"RES-4F17946A-9286-D5F0-7B6A-04E980C04F46\" parameters=\"" + GetParameterString() + "\">" +
                    "			<title>"+ PlayerPrefs.GetString("SCO_Title") + "</title>" +
                    "			 <adlcp:dataFromLMS>"+ PlayerPrefs.GetString("Data_From_Lms") + "</adlcp:dataFromLMS>" +
                    "			 <adlcp:completionThreshold completedByMeasure = \""+ (System.Convert.ToBoolean(PlayerPrefs.GetInt("completedByMeasure"))).ToString().ToLower() + "\" minProgressMeasure= \"" + PlayerPrefs.GetFloat("minProgressMeasure") + "\" />";
                if (PlayerPrefs.GetInt("satisfiedByMeasure") == 1)
                {
                    manifest += "				<imsss:sequencing>"+
                                "			      <imsss:objectives>"+
                                "			        <imsss:primaryObjective objectiveID = \"PRIMARYOBJ\""+
                                "			               satisfiedByMeasure = \""+ (System.Convert.ToBoolean(PlayerPrefs.GetInt("satisfiedByMeasure"))).ToString().ToLower() + "\">" +
                                "			          <imsss:minNormalizedMeasure>"+ PlayerPrefs.GetFloat("minNormalizedMeasure") + "</imsss:minNormalizedMeasure>" +
                                "			        </imsss:primaryObjective>"+
                                "			      </imsss:objectives>"+
                                "			    </imsss:sequencing>";
                }
                manifest +=
                    "      </item>" +
                    "    </organization>" +
                    "  </organizations>" +
                    "  <resources>" +
                    "    <resource identifier=\"RES-4F17946A-9286-D5F0-7B6A-04E980C04F46\" type=\"webcontent\" href=\"WebPlayer/WebPlayer.html\" adlcp:scormType=\"sco\">" +
                    "      <file href=\"WebPlayer/WebPlayer.html\" />" +
                    "      <file href=\"WebPlayer/scripts/scorm.js\" />" +
                    "		<file href=\"WebPlayer/scripts/ScormSimulator.js\" />"+
                    "		<file href=\"WebPlayer/UnityObject.js\" />"+
                    "		<file href=\"WebPlayer/Webplayer.unity3d\" />"+
                    "		<file href=\"WebPlayer/images/scorm_progres_bar.png\" />"+
                    "		<file href=\"WebPlayer/images/thumbnail.png\" />"+
                    "    </resource>" +
                    "  </resources>" +
                    "</manifest>";

                zip.AddEntry("imsmanifest.xml", ".", System.Text.ASCIIEncoding.ASCII.GetBytes(manifest));
            }
            else
            {
                zip.AddItem(Application.dataPath + "/ADL SCORM/Plugins/1.2");
                string manifest =
                    "<?xml version=\"1.0\"?>" +
                    "<!-- exported by Unity-SCORM Integration Toolkit Version 1.4 Beta-->" +
                    "<manifest identifier=\"SingleCourseManifest\" version=\"1.1\"" +
                    "          xmlns=\"http://www.imsproject.org/xsd/imscp_rootv1p1p2\"" +
                    "          xmlns:adlcp=\"http://www.adlnet.org/xsd/adlcp_rootv1p2\"" +
                    "          xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
                    "          xsi:schemaLocation=\"http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd" +
                    "                              http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd" +
                    "                              http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd\">" +
                    "   <organizations default=\"B0\">" +
                    "      <organization identifier=\"B0\">" +
                    "         <title>" + PlayerPrefs.GetString("Course_Title") + "</title>" +
                    "			   <item identifier=\"IS12\" identifierref=\"RS12\" parameters=\""+ GetParameterString() + "\">" +
                    "				  <title>"+ PlayerPrefs.GetString("SCO_Title") + "</title>" +
                    "				  <adlcp:dataFromLMS>"+ PlayerPrefs.GetString("Data_From_Lms") + "</adlcp:dataFromLMS>" +
                    "				  <adlcp:masteryscore>"+ PlayerPrefs.GetFloat("masteryscore") + "</adlcp:masteryscore>" +
                    "			   </item>"+
                    "	      </organization>"+
                    "	   </organizations>"+
                    "	   <resources>"+
                    "	      <resource identifier=\"RS12\" type=\"webcontent\""+
                    "	                adlcp:scormtype=\"sco\" href=\"WebPlayer/WebPlayer.html\">"+
                    "	      </resource>"+
                    "	   </resources>"+
                    "	</manifest>";


                zip.AddEntry("imsmanifest.xml", ".", System.Text.ASCIIEncoding.ASCII.GetBytes(manifest));
            }
            zip.Save();
        }
    }
示例#59
0
        public void Export(bool rewrite = false)
        {
            try
            {
                XmlWriter xmlio;
                if (File.Exists(Filename + ".sft") && rewrite == false)
                {
                    throw new Exceptions.FileExists();
                }
                if (!Directory.Exists("res"))
                {
                    Directory.CreateDirectory("res");
                }
                fs    = new FileStream("script.ist", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                xmlio = XmlWriter.Create(fs);
                sr    = new StreamReader(fs);

                xmlio.WriteStartElement("subject"); //root
                xmlio.WriteAttributeString("name", Name);

                xmlio.WriteStartElement("settings");  //setings part

                xmlio.WriteStartElement("showright"); //define show right after asking on task
                xmlio.WriteString((ShowRight == true) ? "True" : "False");
                xmlio.WriteEndElement();

                xmlio.WriteStartElement("allowremake"); //define can student pass this subject again
                xmlio.WriteString((AllowRemake == true) ? "True" : "False");
                xmlio.WriteEndElement();

                xmlio.WriteStartElement("randomtask"); //define should be task sorted by order or presented randomly
                xmlio.WriteString((Randomtask == true) ? "True" : "False");
                xmlio.WriteEndElement();

                xmlio.WriteStartElement("randomanswer");//define should answers be presented randomly
                xmlio.WriteString((RandomAnswerOrder == true) ? "True" : "False");
                xmlio.WriteEndElement();

                xmlio.WriteStartElement("usetimer");                        //define time to pass task
                xmlio.WriteAttributeString("time", Convert.ToString(Time)); //write time per task, if time wasn't defined, time = -1
                xmlio.WriteString((UseTime == true) ? "True" : "False");
                xmlio.WriteEndElement();

                xmlio.WriteStartElement("limittasks");//define task limitation in one test
                xmlio.WriteAttributeString("tasks", Convert.ToString(LimitedTasksAmount));
                xmlio.WriteString((LimitTasks == true) ? "True" : "False");
                xmlio.WriteEndElement();

                xmlio.WriteEndElement();          //close setings part

                xmlio.WriteStartElement("tasks"); //open tasks part

                foreach (TaskClass task in Tasks)
                {
                    xmlio.WriteStartElement("task");   //define task

                    xmlio.WriteStartElement("header"); //write header of task
                    xmlio.WriteString(task.Label);
                    xmlio.WriteEndElement();

                    xmlio.WriteStartElement("text"); //write text of the task
                    xmlio.WriteString(task.Text);
                    xmlio.WriteEndElement();

                    xmlio.WriteStartElement("images"); //write images pathes

                    int counter = 0;
                    foreach (KeyValuePair <Image, string> img in task.Images)
                    {
                        string path  = @"res/img" + task.Label + counter + ".jpg";
                        Image  image = img.Key;
                        image.Save(path);
                        xmlio.WriteElementString("image", path);
                        counter++;
                    }
                    xmlio.WriteEndElement();

                    xmlio.WriteStartElement("answertype");
                    xmlio.WriteString(Convert.ToString(task.Answer_Type));
                    xmlio.WriteEndElement();

                    xmlio.WriteStartElement("answers");
                    foreach (string answer in task.Answers)
                    {
                        xmlio.WriteStartElement("answer");
                        xmlio.WriteString(answer);
                        xmlio.WriteEndElement();
                    }
                    xmlio.WriteEndElement();

                    xmlio.WriteStartElement("right");
                    xmlio.WriteString(task.Answer);
                    xmlio.WriteEndElement();

                    xmlio.WriteEndElement();//close task
                }
                xmlio.WriteEndElement();
                xmlio.WriteStartElement("marks");
                foreach (MarkClass mrk in Marks)
                {
                    xmlio.WriteStartElement("mark");
                    xmlio.WriteElementString("percentage", Convert.ToString(mrk.Percentage));
                    xmlio.WriteElementString("name", mrk.Mark);
                    xmlio.WriteEndElement();
                }
                xmlio.WriteEndElement();
                xmlio.Flush();
                long   position = fs.Position;
                string has      = CalculateHash();
                fs.Position = position;
                xmlio.WriteStartElement("hashMD5");
                xmlio.WriteString(has);
                xmlio.WriteEndElement();


                xmlio.WriteEndElement();

                xmlio.WriteEndDocument();
                xmlio.Close();

                fs.Close();

                Ionic.Zip.ZipFile zp = new Ionic.Zip.ZipFile();
                zp.AddFile("script.ist");
                zp.AddDirectory("res", "res");
                zp.Save($"{Filename}.sft");

                byte[]      fl = File.ReadAllBytes($"{Filename}.sft");
                byte[]      res;
                List <byte> tmplist = new List <byte>();
                foreach (byte tmp in fl)
                {
                    var vt = ~tmp;
                    tmplist.Add((byte)vt);
                }
                res = tmplist.ToArray();
                File.WriteAllBytes($"{Filename}.sft", res);
                File.Delete("script.ist");
                Directory.Delete("res", true);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"При загрузке .sft файла произошла ошибка \nОписаие ошибки:{ex.Message}");
            }
        }
示例#60
0
        private static bool compressFilesToZip()
        {
            if (Directory.Exists(destinationDirectory + "tmp"))
            {
                int segmentsCreated = 0;
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Encoding.UTF8))
                {
                    if (ZIPpartSizeMB <= 0)
                    {
                        zip.AddDirectory(destinationDirectory + "tmp");
                        zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G");

                        zip.Save(destinationDirectory + ZIPfileSuffixName);

                        segmentsCreated = zip.NumberOfSegmentsForMostRecentSave;
                    }
                }

                if (ZIPpartSizeMB > 0)
                {
                    FileInfo[] files = GetFilesFromDir(destinationDirectory + "tmp", listOfAllowedExtensions);


                    double filesSize = 0;
                    int    part      = 0;
                    int    lastIndex = 0;

                    while (true)
                    {
                        using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Encoding.UTF8))
                        {
                            if (lastIndex == files.Count())
                            {
                                segmentsCreated++;

                                break;
                            }

                            for (int i = lastIndex; i <= files.Count(); i++)
                            {
                                if (lastIndex == files.Count())
                                {
                                    part++;
                                    zip.Save(destinationDirectory + part + "_" + ZIPfileSuffixName);

                                    filesSize = 0;

                                    break;
                                }

                                FileInfo file = files[i];

                                if (file.Length / 1024 > ZIPpartSizeMB * 1024)
                                {
                                    zip.AddFile(file.FullName, "");

                                    filesSize += file.Length / 1024;
                                    lastIndex++;

                                    part++;
                                    zip.Save(destinationDirectory + part + "_" + ZIPfileSuffixName);

                                    filesSize = 0;

                                    break;
                                }


                                if ((ZIPpartSizeMB * 1024 > (filesSize + (file.Length / 1024)) && i < files.Count()))
                                {
                                    zip.AddFile(file.FullName, "");

                                    filesSize += file.Length / 1024;
                                    lastIndex++;
                                }
                                else
                                {
                                    part++;
                                    zip.Save(destinationDirectory + part + "_" + ZIPfileSuffixName);

                                    filesSize = 0;

                                    break;
                                }
                            }
                        }
                    }
                }

                if (segmentsCreated > 0)
                {
                    try
                    {
                        DeleteDirectory(destinationDirectory + "tmp");
                    } catch (IOException ioex)
                    {
                    }

                    return(true);
                }
            }

            return(false);
        }