Пример #1
0
        public string CreateArchive(LanguageConfiguration configuration)
        {
            var tgzFilename = string.Format(TgzFilenameFormat, configuration.BuildNumber);

            this.files.Clear();
            this.files.Add(configuration.AnswerFile);
            this.files.AddRange(configuration.OtherFiles);

            using (var outStream = File.Create(tgzFilename))
                using (var gzoStream = new GZipOutputStream(outStream))
                    using (var tarArchive = TarArchive.CreateOutputTarArchive(gzoStream))
                    {
                        tarArchive.RootPath = Path.GetDirectoryName(configuration.AnswerFile);

                        foreach (var file in this.files)
                        {
                            var tarEntry = TarEntry.CreateEntryFromFile(file);
                            tarEntry.Name = Path.GetFileName(file);

                            tarArchive.WriteEntry(tarEntry, true);
                        }
                    }

            return(tgzFilename);
        }
        public void WriteTarGzipProject(string id, ProjectTarGzipDto projectTarGzipDto, string directory)
        {
            if (directory == null)
            {
                directory = Application.dataPath + "/Card Set Editor Projects/";
            }

            Stream     outStream  = File.Create(directory + id + ".cse-project");
            Stream     gzoStream  = new GZipOutputStream(outStream);
            TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzoStream);

            // Note that the RootPath is currently case sensitive and must be forward slashes e.g. "c:/temp"
            // and must not end with a slash, otherwise cuts off first char of filename
            // This is scheduled for fix in next release
            tarArchive.RootPath = directory.Replace('\\', '/');
            if (tarArchive.RootPath.EndsWith("/"))
            {
                tarArchive.RootPath = tarArchive.RootPath.Remove(tarArchive.RootPath.Length - 1);
            }

            foreach (var cardTarGzipDto in projectTarGzipDto.cardTarGzipDtoList)
            {
                // Add a Copy of these two guys to our tgz
                AddDirectoryFilesToTar(tarArchive, cardTarGzipDto.cardJsonFileDireString);
                AddDirectoryFilesToTar(tarArchive, cardTarGzipDto.cardPNGFileString);
                // Delete the originals
                File.Delete(cardTarGzipDto.cardJsonFileDireString);
                File.Delete(cardTarGzipDto.cardPNGFileString);
            }

            tarArchive.Close();
        }
Пример #3
0
        /// <summary>
        /// Pack the archive
        /// </summary>
        public static Task PackAsync(Recipe recipe, string directory, Stream stream)
        {
            var includePatterns = new List <Glob.Glob>();

            // Include the Recipe file
            includePatterns.Add(new Glob.Glob(Constants.RecipeFileName.ToLower()));

            // Include all or the source filess
            foreach (var source in recipe.Source)
            {
                includePatterns.Add(new Glob.Glob(source.ToLower()));
            }

            using (var gzipStream = new GZipStream(stream, CompressionLevel.Optimal, true))
                using (var archive = TarArchive.CreateOutputTarArchive(gzipStream))
                {
                    archive.RootPath = directory;

                    // Check every file in the directory
                    foreach (var file in Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories))
                    {
                        var  relativePath = Path.GetRelativePath(directory, file);
                        bool matchInclude = includePatterns.Any(pattern => pattern.IsMatch(relativePath.ToLower()));
                        if (matchInclude)
                        {
                            Log.Verbose(relativePath);
                            var entry = TarEntry.CreateEntryFromFile(file);
                            archive.WriteEntry(entry, true);
                        }
                    }
                }

            return(Task.CompletedTask);
        }
Пример #4
0
        private static void CompressTar(
            string directory,
            string archiveFile,
            Predicate <FileInfo> filter,
            FileMode fileMode,
            Func <Stream, Stream> outputStreamFactory)
        {
            Log.Information("Compressing content of {Directory} to {File} ...", directory, Path.GetFileName(archiveFile));

            FileSystemTasks.EnsureExistingParentDirectory(archiveFile);

            var files = GetFiles(directory, filter);

            using var fileStream   = File.Open(archiveFile, fileMode, FileAccess.ReadWrite);
            using var outputStream = outputStreamFactory(fileStream);
            using var tarArchive   = TarArchive.CreateOutputTarArchive(outputStream);

            foreach (var file in files)
            {
                var entry        = TarEntry.CreateEntryFromFile(file);
                var relativePath = PathConstruction.GetRelativePath(directory, file);
                entry.Name = PathConstruction.NormalizePath(relativePath, separator: '/');

                tarArchive.WriteEntry(entry, recurse: false);
            }
        }
Пример #5
0
        public static string CreateTarGz(string tgzFilename, string directory, IProgress <string> progress = null)
        {
            var guid     = Guid.NewGuid();
            var tempPath = Path.Combine(Path.GetTempPath(), guid.ToString());
            var tarPath  = Path.Combine(tempPath, $"{tgzFilename}.tar");

            Directory.CreateDirectory(tempPath);

            using (var outStream = File.Create(tarPath))
                using (var gzoStream = new GZipOutputStream(outStream))
                    using (var tarArchive = TarArchive.CreateOutputTarArchive(gzoStream))
                    {
                        tarArchive.RootPath = Path.GetDirectoryName(directory);

                        var tarEntry = TarEntry.CreateEntryFromFile(directory);
                        tarEntry.Name = Path.GetFileName(directory);

                        tarArchive.ProgressMessageEvent += (archive, entry, message) =>
                        {
                            progress?.Report(message);
                        };

                        tarArchive.WriteEntry(tarEntry, true);
                    }

            return(tarPath);
        }
Пример #6
0
        private void createTARAndTxLog(int partNumber)
        {
            FileInfo fioi   = new FileInfo(fileLogFileDialog.FileName);
            String   slogId = fioi.Name.Replace(".csv", "");

            DateTime dt = new DateTime();

            dt = DateTime.Now;
            String dtString = dt.ToString();

            dtString = dtString.Replace("/", "_").Replace(":", "").Replace(" ", "");

            tarLogName = "GlacierTARBall_" + slogId + "_Part" + Convert.ToString(partNumber) + "_" + dtString + "_LOG.csv";
            tarLog     = new StreamWriter(tarLogName);
            tarLog.WriteLine("Zip FileLoc" + "," + "SHA256 Compressed" + "," + "FileName" + "," + "SHA 256 Decompressed");

            archiveName = "GlacierTARBall_" + slogId + "_Part" + Convert.ToString(partNumber) + "_" + dtString + ".tar";

            log.Info("Making Tar Log : " + "GlacierTarLog_" + slogId + "_Part" + Convert.ToString(partNumber) + "_" + dtString + ".csv");

            log.Info("Tar FileName : " + "GlacierTARBall_" + slogId + "_Part" + Convert.ToString(partNumber) + "_" + dtString + ".tar");

            FileStream fs = File.Create(archiveName);

            TarOutputStream stream = new TarOutputStream((Stream)fs);

            archive = TarArchive.CreateOutputTarArchive(stream);
        }
Пример #7
0
        public static void Make_TAR(string What, string Where)
        {
            string        Out_TAR         = Path.GetFileNameWithoutExtension(Where) + ".tar";
            string        Out_MD5         = Path.GetFileNameWithoutExtension(Where) + ".tar.md5";
            Stream        fs              = new FileStream(Out_MD5, FileMode.Create);
            StringBuilder sb              = new StringBuilder();
            MD5           MD5_Hash_Engine = new MD5CryptoServiceProvider();

            Console.WriteLine("Creating: " + Out_MD5 + " .....");
            TarArchive TA = TarArchive.CreateOutputTarArchive(fs);
            TarEntry   TE = TarEntry.CreateEntryFromFile(What);

            TE.SetIds(0, 0);
            TE.SetNames(string.Empty, string.Empty);
            TE.TarHeader.Mode = 420;
            TA.WriteEntry(TE, true);
            TA.Close();
            fs.Close();
            Stream hash = new FileStream(Out_MD5, FileMode.Open);

            byte[] TAR_MD5_Hash = MD5_Hash_Engine.ComputeHash(hash);
            for (int i = 0; i < TAR_MD5_Hash.Length; i++)
            {
                sb.Append(TAR_MD5_Hash[i].ToString("X2"));
            }
            byte[] Final_Hash = Encoding.ASCII.GetBytes(sb.ToString().ToLower() + Convert.ToChar(0x20).ToString() + Convert.ToChar(0x20).ToString() + Out_TAR + Convert.ToChar("\n").ToString());
            Console.WriteLine("MD5 for " + Out_MD5 + " is " + sb.ToString().ToLower());
            hash.Write(Final_Hash, 0, Final_Hash.Length);
            hash.Close();
        }
Пример #8
0
        private void CreateTarGZ(string tgzFilename, string sourceDirectory)
        {
            try
            {
                Stream     outStream  = File.Create(tgzFilename);
                Stream     gzoStream  = new GZipOutputStream(outStream);
                TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzoStream);

                // Note that the RootPath is currently case sensitive and must be forward slashes e.g. "c:/temp"
                // and must not end with a slash, otherwise cuts off first char of filename
                // This is scheduled for fix in next release
                tarArchive.RootPath = sourceDirectory.Replace('\\', '/');
                if (tarArchive.RootPath.EndsWith("/"))
                {
                    tarArchive.RootPath = tarArchive.RootPath.Remove(tarArchive.RootPath.Length - 1);
                }

                AddDirectoryFilesToTar(tarArchive, sourceDirectory, true);

                tarArchive.Close();
            }
            catch (SystemException se)
            {
                MessageBox.Show(se.Message);
            }
        }
Пример #9
0
        static void FileBackup(string dbPath, string dbName)
        {
            var backup = Path.Combine(App.Current.DBDir, "backup");

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

            string outputFilename = Path.Combine(backup, dbName + ".tar.gz");

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

            // storage backup in old format
            using (FileStream fs = new FileStream(outputFilename, FileMode.Create, FileAccess.Write, FileShare.None)) {
                using (Stream gzipStream = new GZipOutputStream(fs)) {
                    using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzipStream)) {
                        foreach (string n in new string [] { "", "-wal", "-shm" })
                        {
                            TarEntry tarEntry = TarEntry.CreateEntryFromFile(Path.Combine(dbPath, dbName + ".cblite" + n));
                            tarArchive.WriteEntry(tarEntry, true);
                        }
                        AddDirectoryFilesToTar(tarArchive, Path.Combine(dbPath, dbName + " attachments"), true);
                    }
                }
            }
        }
Пример #10
0
 /// <summary>
 /// Creates a GZipped Tar file from a source directory
 /// </summary>
 /// <param name="outputTarFilename">Output .tar.gz file</param>
 /// <param name="sourceDirectory">Input directory containing files to be added to GZipped tar archive</param>
 public static void CreateTar(string outputTarFilename, string sourceDirectory)
 {
     using (FileStream fs = new FileStream(outputTarFilename, FileMode.Create, FileAccess.Write, FileShare.None))
         using (Stream gzipStream = new GZipOutputStream(fs))
             using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzipStream))
                 AddDirectoryFilesToTar(tarArchive, sourceDirectory, true);
 }
Пример #11
0
        public void EmptyTar()
        {
            var ms         = new MemoryStream();
            int recordSize = 0;

            using (TarArchive tarOut = TarArchive.CreateOutputTarArchive(ms))
            {
                recordSize = tarOut.RecordSize;
            }

            Assert.IsTrue(ms.GetBuffer().Length > 0, "Archive size must be > zero");
            Assert.Zero(ms.GetBuffer().Length % recordSize, "Archive size must be a multiple of record size");

            var ms2 = new MemoryStream();

            ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
            ms2.Seek(0, SeekOrigin.Begin);

            using (TarArchive tarIn = TarArchive.CreateInputTarArchive(ms2, null))
            {
                entryCount = 0;
                tarIn.ProgressMessageEvent += EntryCounter;
                tarIn.ListContents();
                Assert.AreEqual(0, entryCount, "Expected 0 tar entries");
            }
        }
Пример #12
0
        public string CreateArchive(string solutionPath, string buildId)
        {
            if (solutionPath == null)
            {
                throw new ArgumentNullException(nameof(solutionPath));
            }

            var tgzFilename = string.Format(TgzFilenameFormat, buildId);

            try
            {
                var files = Directory.GetFiles(solutionPath);

                using (var outStream = File.Create(tgzFilename))
                    using (var gzoStream = new GZipOutputStream(outStream))
                        using (var tarArchive = TarArchive.CreateOutputTarArchive(gzoStream))
                        {
                            tarArchive.RootPath = Path.GetDirectoryName(solutionPath);

                            foreach (var file in files)
                            {
                                var tarEntry = TarEntry.CreateEntryFromFile(file);
                                tarEntry.Name = Path.GetFileName(file);

                                tarArchive.WriteEntry(tarEntry, true);
                            }
                        }
            }
            catch (Exception ex)
            {
                throw new CodeNotAchivedException($"Не удалось создать архив для {solutionPath}", ex);
            }

            return(tgzFilename);
        }
Пример #13
0
        private void CreateTarArchive()
        {
            log.Trace("TAR (Create): '{0}' -> '{1}'", directory, tarFile);

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

            using (var fs = File.Open(tarFile, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                using (var gzipStream = new GZipOutputStream(fs))
                {
                    using (var tarArchive = TarArchive.CreateOutputTarArchive(gzipStream))
                    {
                        tarArchive.RootPath = directory.Replace('\\', '/');
                        if (tarArchive.RootPath.EndsWith("/"))
                        {
                            tarArchive.RootPath = tarArchive.RootPath.Remove(tarArchive.RootPath.Length - 1);
                        }

                        var tarEntry = TarEntry.CreateEntryFromFile(directory);
                        tarArchive.WriteEntry(tarEntry, true);

                        log.Debug("TAR DIRECTORY {0}", directory);
                        log.Debug("TAR ROOT {0}", tarArchive.RootPath);
                    }
                }
            }
        }
        /// <summary>
        /// 生成 ***.tar.gz 文件
        /// </summary>
        /// <param name="sourceFolderPath">待压缩的源文件夹或文件路径</param>
        /// <param name="tgzFileDir">生成的文件路径</param>
        /// <param name="tgzFileName">生成的文件名称,不带扩展名</param>
        /// <param name="encoding">编码</param>
        /// <returns></returns>
        public bool CreateTarGzArchive(string sourceFolderPath, string tgzFileDir, string tgzFileName = "temp", string encoding = "utf-8")
        {
            if (!System.IO.Directory.Exists(tgzFileDir))
            {
                System.IO.Directory.CreateDirectory(tgzFileDir);
            }

            //string fileName;
            //if (File.Exists(sourceFolderPath))  // 如果是文件
            //{
            //    fileName = Path.GetFileNameWithoutExtension(sourceFolderPath);
            //}
            //else
            //{
            //    string tempStr = sourceFolderPath.Replace('\\', '/');
            //    Regex regex = new Regex("/(.+?)$", RegexOptions.RightToLeft);
            //    fileName = regex.Match(tempStr).Groups[1].Value;
            //}

            tgzFileName = Path.Combine(tgzFileDir, tgzFileName + ".tar.gz");

            using Stream outTmpStream = new FileStream(tgzFileName, FileMode.OpenOrCreate);

            //注意此处源文件大小大于4096KB
            using Stream outStream   = new GZipOutputStream(outTmpStream);
            using TarArchive archive = TarArchive.CreateOutputTarArchive(outStream, TarBuffer.DefaultBlockFactor, Encoding.GetEncoding(encoding));
            archive.RootPath         = Path.GetDirectoryName(sourceFolderPath);
            TarEntry entry = TarEntry.CreateEntryFromFile(sourceFolderPath);

            archive.WriteEntry(entry, true);

            return(true);
        }
Пример #15
0
        public static void Create(string sourcePath, string targetPath)
        {
            var previousDirectory = Environment.CurrentDirectory;

            try
            {
                using (var outStream = File.Open(targetPath, FileMode.Create))
                    using (var gzoStream = new GZipOutputStream(outStream))
                        using (var tarArchive = TarArchive.CreateOutputTarArchive(gzoStream))
                        {
                            if (Directory.Exists(sourcePath)) // is directory
                            {
                                Environment.CurrentDirectory = sourcePath;
                                tarArchive.AddDirectory(sourcePath);
                            }
                            else
                            {
                                Environment.CurrentDirectory = Path.GetDirectoryName(sourcePath);
                                tarArchive.AddFile(sourcePath);
                            }
                        }
            }
            finally
            {
                Environment.CurrentDirectory = previousDirectory;
            }
        }
Пример #16
0
 /// <summary>
 /// files to gzip
 /// </summary>
 /// <param name="tgzFileName">tgzFileName.</param>
 /// <param name="files">files.</param>
 /// <param name="rootPath">rootPath.</param>
 public static void CreateGZip(string tgzFileName, List <String> files, string rootPath = null)
 {
     if (string.IsNullOrEmpty(rootPath))
     {
         rootPath = CUtils.realStreamingAssetsPath;
     }
     rootPath = rootPath.Replace('\\', '/');
     if (rootPath.EndsWith("/"))
     {
         rootPath = rootPath.Remove(rootPath.Length - 1);
     }
     if (File.Exists(tgzFileName))
     {
         File.Delete(tgzFileName);
     }
     using (Stream outStream = File.Create(tgzFileName))
     {
         using (GZipOutputStream gzoStream = new GZipOutputStream(outStream))
         {
             TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzoStream);
             tarArchive.RootPath = rootPath;
             foreach (string filename in files)
             {
                 //check folder
                 AddDirectoryFilesToTar(tarArchive, rootPath, filename);
             }
         }
     }
 }
        /// <inheritdoc />
        public string Tar()
        {
            var dockerfileArchiveName = Regex.Replace(this.image.FullName, "[^a-zA-Z0-9]", "-").ToLowerInvariant();

            var dockerfileArchivePath = Path.Combine(Path.GetTempPath(), $"{dockerfileArchiveName}.tar");

            var dockerIgnoreFile = new DockerIgnoreFile(this.dockerfileDirectory.FullName, ".dockerignore", this.logger);

            using (var stream = new FileStream(dockerfileArchivePath, FileMode.Create))
            {
                using (var tarArchive = TarArchive.CreateOutputTarArchive(stream))
                {
                    tarArchive.RootPath = OS.NormalizePath(this.dockerfileDirectory.FullName);

                    foreach (var file in GetFiles(this.dockerfileDirectory.FullName))
                    {
                        var relativePath = file.Substring(tarArchive.RootPath.Length + 1);

                        if (dockerIgnoreFile.Denies(relativePath))
                        {
                            continue;
                        }

                        var tarEntry = TarEntry.CreateEntryFromFile(file);
                        tarEntry.Name = relativePath;
                        tarArchive.WriteEntry(tarEntry, true);
                    }
                }
            }

            return(dockerfileArchivePath);
        }
Пример #18
0
        /// <summary>
        /// 生成 ***.tar 文件
        /// </summary>
        /// <param name="strBasePath">文件基目录(源文件、生成文件所在目录)</param>
        /// <param name="strSourceFolderName">待压缩的源文件夹名</param>
        public bool CreatTarArchive(string strBasePath, string strSourceFolderName)
        {
            if (string.IsNullOrEmpty(strBasePath) ||
                string.IsNullOrEmpty(strSourceFolderName) ||
                !System.IO.Directory.Exists(strBasePath) ||
                !System.IO.Directory.Exists(Path.Combine(strBasePath, strSourceFolderName)))
            {
                return(false);
            }
            Environment.CurrentDirectory = strBasePath;                                              //要压缩的文件夹名称
            string strSourceFolderAllPath = Path.Combine(strBasePath, strSourceFolderName);
            string strOupFileAllPath      = Path.Combine(strBasePath, strSourceFolderName + ".tar"); //压缩文件名及路径

            Stream outStream = new FileStream(strOupFileAllPath, FileMode.OpenOrCreate);

            TarArchive archive = TarArchive.CreateOutputTarArchive(outStream, TarBuffer.DefaultBlockFactor);
            TarEntry   entry   = TarEntry.CreateEntryFromFile(strSourceFolderAllPath);

            archive.WriteEntry(entry, true);

            if (archive != null)
            {
                archive.Close();
            }

            outStream.Close();

            return(true);
        }
Пример #19
0
        public override void CreateTarFromLocalData(string outputPath)
        {
            lock (_pathsPreparedForRemote)
            {
                UpdatePathsPreparedForRemote();

                if (_pathsPreparedForRemote.Count == 0)
                {
                    throw new Exception("No data available.");
                }

                using (FileStream outputFile = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
                {
                    using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(outputFile))
                    {
                        foreach (string pathPreparedForRemote in _pathsPreparedForRemote)
                        {
                            using (FileStream filePreparedForRemote = File.OpenRead(pathPreparedForRemote))
                            {
                                TarEntry tarEntry = TarEntry.CreateEntryFromFile(pathPreparedForRemote);
                                tarEntry.Name = "data/" + Path.GetFileName(pathPreparedForRemote);
                                tarArchive.WriteEntry(tarEntry, false);
                                filePreparedForRemote.Close();
                            }
                        }

                        tarArchive.Close();
                    }

                    outputFile.Close();
                }
            }
        }
Пример #20
0
        /// <summary>
        /// 打包成Tar包
        /// </summary>
        /// <param name="strBasePath">压缩文件夹路径</param>
        /// <param name="strSourceFolderName">生成tar文件路径</param>
        /// <param name="sTarName">生成tar文件名称</param>
        /// <returns></returns>
        public bool CreatTarArchive(string strBasePath, string strSourceFolderName, string sTarName)
        {
            if (!Directory.Exists(strSourceFolderName))
            {
                Directory.CreateDirectory(strSourceFolderName);//不存在生成Tar文件目录就创建
            }

            if (string.IsNullOrEmpty(strBasePath) ||
                string.IsNullOrEmpty(strSourceFolderName) ||
                !Directory.Exists(strBasePath))
            {
                return(false);
            }
            if (strBasePath.EndsWith("\\"))
            {
                strBasePath = strSourceFolderName.TrimEnd('\\');
            }
            Environment.CurrentDirectory = strBasePath;                                     //要压缩的文件夹名称
            string strSourceFolderAllPath = strBasePath;
            string strOupFileAllPath      = strSourceFolderName + "\\" + sTarName + ".tar"; //压缩文件名及路径

            Stream outStream = new FileStream(strOupFileAllPath, FileMode.OpenOrCreate);

            TarArchive archive = TarArchive.CreateOutputTarArchive(outStream, TarBuffer.DefaultBlockFactor);
            TarEntry   entry   = TarEntry.CreateEntryFromFile(strSourceFolderAllPath);

            archive.WriteEntry(entry, true);

            if (archive != null)
            {
                archive.Close();
            }
            outStream.Close();
            return(true);
        }
Пример #21
0
        public void RootPathIsRespected()
        {
            using (var extractDirectory = new Utils.TempDir())
                using (var tarFileName = new Utils.TempFile())
                    using (var tempDirectory = new Utils.TempDir())
                    {
                        tempDirectory.CreateDummyFile();

                        using (var tarFile = File.Open(tarFileName.Filename, FileMode.Create))
                        {
                            using (var tarOutputStream = TarArchive.CreateOutputTarArchive(tarFile))
                            {
                                tarOutputStream.RootPath = tempDirectory.Fullpath;
                                var entry = TarEntry.CreateEntryFromFile(tempDirectory.Fullpath);
                                tarOutputStream.WriteEntry(entry, true);
                            }
                        }

                        using (var file = File.OpenRead(tarFileName.Filename))
                        {
                            using (var archive = TarArchive.CreateInputTarArchive(file, Encoding.UTF8))
                            {
                                archive.ExtractContents(extractDirectory.Fullpath);
                            }
                        }

                        var expectationDirectory = new DirectoryInfo(tempDirectory.Fullpath);
                        foreach (var checkFile in expectationDirectory.GetFiles("", SearchOption.AllDirectories))
                        {
                            var relativePath = checkFile.FullName.Substring(expectationDirectory.FullName.Length + 1);
                            FileAssert.Exists(Path.Combine(extractDirectory.Fullpath, relativePath));
                            FileAssert.AreEqual(checkFile.FullName, Path.Combine(extractDirectory.Fullpath, relativePath));
                        }
                    }
        }
Пример #22
0
        private void CreateTar(string path, int id) // Пакует в архив заказ по имени архива, пути до папки файлов и id
        {
            using (var outStream = File.Create(nextID.ToString()))
                //using (var gzoStream = new GZipOutputStream(outStream))
                using (var tarArchive = TarArchive.CreateOutputTarArchive(outStream))
                {
                    string s = "nope";
                    try
                    {
                        tarArchive.RootPath = Path.GetDirectoryName("info.txt"); // Пакуем info
                        var tarEntry = TarEntry.CreateEntryFromFile("info.txt");
                        tarEntry.Name = Path.GetFileName("info.txt");
                        tarArchive.WriteEntry(tarEntry, true);
                        s = "+info";

                        tarArchive.RootPath = Path.GetDirectoryName(@"C:\users\masch01\" + orders[id].name + ".LST"); // Пакуем LST #TODO
                        tarEntry            = TarEntry.CreateEntryFromFile(@"C:\users\masch01\" + orders[id].name + ".LST");
                        tarEntry.Name       = Path.GetFileName("PROG.LST");
                        tarArchive.WriteEntry(tarEntry, true);
                        s = "done";
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.ToString(), s);
                    }
                }
            nextID++;
        }
Пример #23
0
        internal static void CompressFolder(string inFolder, string outFile, CompressionFormat format, List <Regex> ignoredPathsRegex)
        {
            string tarFilePath = outFile + "tmptar";

            // Source: https://github.com/icsharpcode/SharpZipLib/wiki/GZip-and-Tar-Samples#-create-a-tgz-targz
            using (FileStream outputStream = File.Create(tarFilePath))
                using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(outputStream))
                {
                    // Currently, SharpZipLib only supports '/', and the folder path must not end with it
                    if (inFolder[inFolder.Length - 1] == '\\' || inFolder[inFolder.Length - 1] == '/')
                    {
                        inFolder = inFolder.Substring(0, inFolder.Length - 1).Replace('\\', '/');
                    }
                    else
                    {
                        inFolder = inFolder.Replace('\\', '/');
                    }

                    tarArchive.RootPath = inFolder;
                    CreateTarRecursive(tarArchive, new DirectoryInfo(inFolder), "", ignoredPathsRegex);
                }

            CompressFile(tarFilePath, outFile, format);
            File.Delete(tarFilePath);
        }
Пример #24
0
        private static void CreateTarGz(string tgzFilename, string sourceDirectory)
        {
            Stream outStream = null;

            try
            {
                outStream = File.Create(tgzFilename);
                var gzoStream = new GZipOutputStream(outStream);
                using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzoStream))
                {
                    outStream = null;
                    // Note that the RootPath is currently case sensitive and must be forward slashes e.g. "c:/temp"
                    // and must not end with a slash, otherwise cuts off first char of filename
                    // This is scheduled for fix in next release
                    tarArchive.RootPath = sourceDirectory.Replace('\\', '/');
                    if (tarArchive.RootPath.EndsWith("/"))
                    {
                        tarArchive.RootPath = tarArchive.RootPath.Remove(tarArchive.RootPath.Length - 1);
                    }

                    AddDirectoryFilesToTar(tarArchive, sourceDirectory, true);
                }
            }
            finally
            {
                if (outStream != null)
                {
                    outStream.Dispose();
                }
            }
        }
Пример #25
0
        public static void CompressFolderLZMA(string inFolder, string outFile)
        {
            string tarFilePath = outFile + "tmptar";

            // Source: https://github.com/icsharpcode/SharpZipLib/wiki/GZip-and-Tar-Samples#-create-a-tgz-targz
            using (FileStream outputStream = File.Create(tarFilePath))
                using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(outputStream))
                {
                    // Currently, SharpZipLib only supports '/', and the folder path must not end with it
                    if (inFolder[inFolder.Length - 1] == '\\' || inFolder[inFolder.Length - 1] == '/')
                    {
                        inFolder = inFolder.Substring(0, inFolder.Length - 1).Replace('\\', '/');
                    }
                    else
                    {
                        inFolder = inFolder.Replace('\\', '/');
                    }

                    tarArchive.RootPath = inFolder;
                    CreateTarRecursive(tarArchive, inFolder);
                }

            CompressFileLZMA(tarFilePath, outFile);
            File.Delete(tarFilePath);
        }
Пример #26
0
        public static void Compress(string directory, string command, string destination)
        {
            if (!Directory.Exists(directory))
            {
                return;
            }

            var filesDirectory = Path.Combine(directory, command + "-files");
            var file           = destination + ".oipkg";

            if (Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix)
            {
                var args = new StringBuilder();
                args.Append("\"" + file + "\" ");
                Directory
                .GetFiles(directory, command + ".*")
                .ToList()
                .ForEach(x => args.Append("\"" + toRelative(x, directory) + "\" "));
                args.Append("\"" + toRelative(filesDirectory, directory) + "\"");
                run(directory, "tar", "-czf " + args.ToString());
                return;
            }

            var currentDirectory = Directory.GetCurrentDirectory();

            Directory.SetCurrentDirectory(directory);
            try
            {
                var outStream  = File.Create(file);
                var gzoStream  = new GZipOutputStream(outStream);
                var tarArchive = TarArchive.CreateOutputTarArchive(gzoStream);

                // Note that the RootPath is currently case sensitive and must be forward slashes e.g. "c:/temp"
                // and must not end with a slash, otherwise cuts off first char of filename
                // This is scheduled for fix in next release
                tarArchive.RootPath = directory.Replace('\\', '/');
                if (tarArchive.RootPath.EndsWith("/"))
                {
                    tarArchive.RootPath = tarArchive.RootPath.Remove(tarArchive.RootPath.Length - 1);
                }

                Directory
                .GetFiles(directory, command + ".*")
                .ToList()
                .ForEach(x => addFile(tarArchive, x));
                addDirectory(tarArchive, filesDirectory);

                tarArchive.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("error|Exception during processing {0}", ex);
                throw;
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDirectory);
            }
        }
Пример #27
0
 private static void Compress(string outputFile, string tempPath)
 {
     using var stream    = new FileStream(outputFile, FileMode.CreateNew);
     using var zipStream = new GZipOutputStream(stream);
     using var archive   = TarArchive.CreateOutputTarArchive(zipStream);
     archive.RootPath    = tempPath;
     archive.AddFilesRecursive(tempPath);
 }
Пример #28
0
 public void CreateTarGzFromDirectory(string sourceDirectory, string targetTarGzFilepath, bool isRecursive)
 {
     using (FileStream fs = new FileStream(targetTarGzFilepath, FileMode.Create, FileAccess.Write, FileShare.None))
         using (Stream gzipStream = new GZipOutputStream(fs))
             using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzipStream))
             {
                 AddDirectoryFilesToTar(tarArchive, sourceDirectory, isRecursive);
             }
 }
Пример #29
0
        static void Zip()
        {
            Stream     outstream  = File.Create(basepath + latest + "\\data.tar.gz");
            Stream     gzipstream = new GZipOutputStream(outstream);
            TarArchive tar        = TarArchive.CreateOutputTarArchive(gzipstream);

            AddDirectoryFilesToTar(tar, dstpath);

            tar.Close();
        }
Пример #30
0
        static async Task Main(string[] args)
        {
            var client = new DockerClientConfiguration(new Uri("http://host.docker.internal:2375"))
                         .CreateClient();

            var sb = new StringBuilder();

            sb.AppendLine("FROM mcr.microsoft.com/dotnet/core/runtime:3.0-buster-slim");
            sb.AppendLine("COPY . .");
            sb.AppendLine("ENTRYPOINT [\"dotnet\", \"Playground.Docker.Hello.dll\"]");

            Directory.Delete("contents", true);

            var contentsDir = Directory.CreateDirectory("contents");

            var dockerfilePath = Path.Combine("contents", "Dockerfile");

            File.WriteAllText(dockerfilePath, sb.ToString());

            File.Copy("Playground.Docker.Hello.dll", Path.Combine("contents", "Playground.Docker.Hello.dll"));
            File.Copy("Playground.Docker.Hello.runtimeconfig.json", Path.Combine("contents", "Playground.Docker.Hello.runtimeconfig.json"));

            var filesInDirectory = contentsDir.GetFiles();
            var tarArchiveName   = @"contents.tar.gz";

            using var targetStream = new GZipOutputStream(File.Create(tarArchiveName));
            {
                using var tarArchive = TarArchive.CreateOutputTarArchive(targetStream);
                {
                    foreach (var fileToBeTarred in filesInDirectory)
                    {
                        var entry = TarEntry.CreateEntryFromFile(fileToBeTarred.FullName);
                        entry.Name = fileToBeTarred.Name;
                        tarArchive.WriteEntry(entry, true);
                    }
                }
            }

            using var contentsStream = File.OpenRead(tarArchiveName);

            var logStream = await client.Images.BuildImageFromDockerfileAsync(contentsStream, new ImageBuildParameters
            {
                Tags = new[] { "playground-hello" }
            });


            var response = await client.Containers.CreateContainerAsync(new CreateContainerParameters
            {
                Image = "playground-hello"
            });

            var started = await client.Containers.StartContainerAsync(response.ID, new ContainerStartParameters
            {
            });
        }