public void InputStreamOwnership() { var memStream = new TrackedMemoryStream(); var s = new TarInputStream(memStream, null); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); s.Close(); Assert.IsTrue(memStream.IsClosed, "Should be closed after parent owner close"); Assert.IsTrue(memStream.IsDisposed, "Should be disposed after parent owner close"); memStream = new TrackedMemoryStream(); s = new TarInputStream(memStream, null); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); s.IsStreamOwner = false; s.Close(); Assert.IsFalse(memStream.IsClosed, "Should not be closed after parent owner close"); Assert.IsFalse(memStream.IsDisposed, "Should not be disposed after parent owner close"); }
internal static void ToFolder(string targetDir, MemoryStream tarStream) { var inputTarStream = new TarInputStream(tarStream); TarEntry tarEntry; while ((tarEntry = inputTarStream.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } var name = SanitizeName(tarEntry.Name); if (Path.IsPathRooted(name)) { name = name.Substring(Path.GetPathRoot(name).Length); } var outName = Path.Combine(targetDir, name); var directoryName = Path.GetDirectoryName(outName); Directory.CreateDirectory(directoryName); var outStr = new FileStream(outName, FileMode.Create); inputTarStream.CopyEntryContents(outStr); outStr.Close(); } inputTarStream.Close(); }
internal static void Extract(System.IO.Stream tarStream, Models.FileTransportInfo fileTransferInfo) { using (TarInputStream tarIn = new TarInputStream(tarStream)) { TarEntry tarEntry = null; while ((tarEntry = tarIn.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } string name = tarEntry.Name.Replace('/', System.IO.Path.DirectorySeparatorChar); if (System.IO.Path.IsPathRooted(name)) { name = name.Substring(System.IO.Path.GetPathRoot(name).Length); } string outName = System.IO.Path.Combine(fileTransferInfo.DestinationFullNameWithBasePath, name); string directoryName = System.IO.Path.GetDirectoryName(outName); System.IO.Directory.CreateDirectory(directoryName); System.IO.FileStream outStr = new System.IO.FileStream(outName, System.IO.FileMode.Create); tarIn.CopyEntryContents(outStr); outStr.Close(); DateTime myDt = DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc); System.IO.File.SetLastWriteTimeUtc(outName, myDt); } tarIn.Close(); } }
static void ReadFromBundle() { using var inStream = File.OpenRead("bundle-example.tar.gz"); // by default would be bundle.tar.gz using var gzipStream = new GZipInputStream(inStream); using var tarStream = new TarInputStream(gzipStream); TarEntry current = null; MemoryStream ms = null; while (null != (current = tarStream.GetNextEntry())) { if ("/policy.wasm" == current.Name) { ms = new MemoryStream(); tarStream.CopyEntryContents(ms); break; } } tarStream.Close(); gzipStream.Close(); inStream.Close(); if (null != ms) { ms.Position = 0; var bytes = ms.ToArray(); int length = bytes.Length; // 554984 } }
/// <summary> /// Tar files only support sequential access! /// </summary> /// <param name="tarFileName">The tar file</param> /// <param name="file">The file to extract</param> /// <param name="targetDir">The destination directory</param> public void ExtractTarByEntry(string tarFileName, string file, string targetDir) { using (FileStream fsIn = new FileStream(tarFileName, FileMode.Open, FileAccess.Read)) { TarInputStream tarIn = new TarInputStream(fsIn); TarEntry tarEntry; while ((tarEntry = tarIn.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } if (tarEntry.Name != file) { continue; } // Apply further name transformations here as necessary string outName = Path.Combine(targetDir, file); using (FileStream outStr = new FileStream(outName, FileMode.Create)) { tarIn.CopyEntryContents(outStr); } } tarIn.Close(); } }
public void InputStreamOwnership() { var memStream = new TrackedMemoryStream(); var s = new TarInputStream(memStream); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); #if NET451 s.Close(); #elif NETCOREAPP1_0 s.Dispose(); #endif Assert.IsTrue(memStream.IsClosed, "Should be closed after parent owner close"); Assert.IsTrue(memStream.IsDisposed, "Should be disposed after parent owner close"); memStream = new TrackedMemoryStream(); s = new TarInputStream(memStream); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); s.IsStreamOwner = false; #if NET451 s.Close(); #elif NETCOREAPP1_0 s.Dispose(); #endif Assert.IsFalse(memStream.IsClosed, "Should not be closed after parent owner close"); Assert.IsFalse(memStream.IsDisposed, "Should not be disposed after parent owner close"); }
private void processTask(RestoreTask task) { Logger.Debug("StorageThread:processTask:RestoreTask"); Stream inStream = File.OpenRead(task.ArchivePath); Stream gzipStream = new GZipInputStream(inStream); TarInputStream tarStream = new TarInputStream(gzipStream); TarEntry entry; List <string> list = task.RelativeFilenames(); RecoverResult recover = new RecoverResult(task.OutputDir, true); while ((entry = tarStream.GetNextEntry()) != null) { if (entry.IsDirectory) { continue; } if (list.IndexOf(entry.Name) != -1) { string name = entry.Name.Replace('/', Path.DirectorySeparatorChar); name = Path.Combine(task.OutputDir, name); Directory.CreateDirectory(Path.GetDirectoryName(name)); FileStream outStream = new FileStream(name, FileMode.CreateNew); tarStream.CopyEntryContents(outStream); outStream.Close(); DateTime myDt = DateTime.SpecifyKind(entry.ModTime, DateTimeKind.Utc); File.SetLastWriteTime(name, myDt); } } tarStream.Close(); lock (_lock) { recoverResults.Enqueue(recover); } }
public bool FileExistsApi(string source, string filename) { using (FileStream fsIn = new FileStream(source, FileMode.Open, FileAccess.Read)) { TarInputStream tarIn = new TarInputStream(fsIn); TarEntry tarEntry; while ((tarEntry = tarIn.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } if (tarEntry.Name == filename) { return(true); } } tarIn.Close(); } return(false); }
void ProcessTarGzFile(string filename) { WriteOnce.SafeLog(string.Format("Analyzing .tar.gz file: [{0}]", filename), LogLevel.Trace); _appProfile.MetaData.TotalFiles = GetTarGzFileCount(filename); using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read)) using (var gzipStream = new GZipInputStream(fileStream)) using (var memoryStream = new MemoryStream()) { var tarStream = new TarInputStream(gzipStream); TarEntry tarEntry; while ((tarEntry = tarStream.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } tarStream.CopyEntryContents(memoryStream); if (tarEntry.Size > MAX_FILESIZE) { _appProfile.MetaData.FilesSkipped++; WriteOnce.SafeLog(string.Format("{0} in {1} is too large. File skipped", tarEntry.Name, filename), LogLevel.Error); tarStream.Close(); continue; } var mimeType = MimeTypeMap.GetMimeType(Path.GetExtension(tarEntry.Name)); if (IgnoreMimeRegex.IsMatch(mimeType) && new FileInfo(filename).Extension != "ts") { _appProfile.MetaData.FilesSkipped++; WriteOnce.SafeLog(string.Format("Ignoring tar entry [{0}]", tarEntry.Name), LogLevel.Error); } else { //file name may contain slashes; remove prior to call byte[] streamByteArray = memoryStream.ToArray(); ProcessInMemory(Path.GetFileName(tarEntry.Name), Encoding.UTF8.GetString(streamByteArray, 0, streamByteArray.Length)); } memoryStream.SetLength(0); // Clear out the stream } tarStream.Close(); } }
/// <summary> /// tar包解压 /// </summary> /// <param name="strFilePath">tar包路径</param> /// <param name="strUnpackDir">解压到的目录</param> /// <returns></returns> public bool UnpackTarFiles(string strFilePath, string strUnpackDir) { try { if (!File.Exists(strFilePath)) { return(false); } strUnpackDir = strUnpackDir.Replace("/", "\\"); if (!strUnpackDir.EndsWith("\\")) { strUnpackDir += "\\"; } if (!Directory.Exists(strUnpackDir)) { Directory.CreateDirectory(strUnpackDir); } FileStream fr = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); TarInputStream s = new TarInputStream(fr); TarEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); if (directoryName != String.Empty) { Directory.CreateDirectory(strUnpackDir + directoryName); } if (fileName != String.Empty) { FileStream streamWriter = File.Create(strUnpackDir + theEntry.Name); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } s.Close(); fr.Close(); return(true); } catch (Exception) { return(false); } }
public static void UnTar(string TarName) { TarInputStream s = null; try { FileInfo fi = new FileInfo(TarName); s = new TarInputStream(File.OpenRead(TarName)); TarEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string FullName = String.Format("{0}\\{1}", fi.DirectoryName, theEntry.Name); string DirName = Path.GetDirectoryName(FullName); string FileName = Path.GetFileName(FullName); if (!Directory.Exists(DirName)) { Directory.CreateDirectory(DirName); } if (FileName != String.Empty) { FileStream SW = File.Create(FullName); int Size = 2048; byte[] data = new byte[2048]; while (true) { Size = s.Read(data, 0, data.Length); if (Size > 0) { SW.Write(data, 0, Size); } else { break; } } SW.Close(); } } } catch { //throw; } finally { s.Close(); } }
/// <summary> /// 解包TAR文件 /// </summary> /// <param name="sourceFilePath">文件的路径</param> /// <param name="targetDirectoryPath">解包的输出路径</param> public static void DecompressTarFile(string sourceFilePath, string targetDirectoryPath) { //检查路径拼写 if (!targetDirectoryPath.EndsWith("\\")) { targetDirectoryPath += "\\"; } using (TarInputStream tarFile = new TarInputStream(File.OpenRead(sourceFilePath))) { TarEntry tarEntry = null; //获取tar文件信息 while ((tarEntry = tarFile.GetNextEntry()) != null) { string directoryName = ""; string pathToTar = tarEntry.Name; if (!string.IsNullOrEmpty(pathToTar)) { //获取文件夹名 directoryName = Path.GetDirectoryName(pathToTar) + "\\"; } //直接创建文件夹由Directory判断是否创建 Directory.CreateDirectory(targetDirectoryPath + directoryName); string fileName = Path.GetFileName(pathToTar); if (!string.IsNullOrEmpty(fileName)) { if (File.Exists(targetDirectoryPath + directoryName + fileName) || !File.Exists(targetDirectoryPath + directoryName + fileName)) { using (FileStream outStream = File.Create(targetDirectoryPath + directoryName + fileName)) { byte[] data = new byte[2048]; while (true) { int bufSize = tarFile.Read(data, 0, data.Length); if (bufSize > 0) { outStream.Write(data, 0, bufSize); } else { break; } } outStream.Close(); } } } } tarFile.Close(); } }
/// <summary> /// 指定されたtar内のファイルを指定フォルダに展開する /// <see cref="https://github.com/icsharpcode/SharpZipLib/wiki/GZip-and-Tar-Samples#extractFull"/> /// </summary> /// <param name="gzStream">ストリーム</param> /// <param name="targetDir">ターゲットフォルダ</param> /// <param name="asciiTranslate">アスキー変換をおこなうかどうかのフラグ</param> public static void ExtractTarByEntry(Stream inStream, string targetDir, bool asciiTranslate) { TarInputStream tarIn = new TarInputStream(inStream); TarEntry tarEntry; while ((tarEntry = tarIn.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } // Converts the unix forward slashes in the filenames to windows backslashes string name = tarEntry.Name.Replace('/', Path.DirectorySeparatorChar); // Remove any root e.g. '\' because a PathRooted filename defeats Path.Combine if (Path.IsPathRooted(name)) { name = name.Substring(Path.GetPathRoot(name).Length); } // Apply further name transformations here as necessary string outName = Path.Combine(targetDir, name); // アイコンファイル以外は展開しない if (!Path.GetFileName(outName).Equals(".icon.png")) { continue; } string directoryName = Path.GetDirectoryName(outName); Directory.CreateDirectory(directoryName); // Does nothing if directory exists FileStream outStr = new FileStream(outName, FileMode.Create); if (asciiTranslate) { CopyWithAsciiTranslate(tarIn, outStr); } else { tarIn.CopyEntryContents(outStr); } outStr.Close(); // Set the modification date/time. This approach seems to solve timezone issues. DateTime myDt = DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc); File.SetLastWriteTime(outName, myDt); } tarIn.Close(); }
public void ExtractFolderFromArchive(FileInfo file, DirectoryInfo targetDirectory) { using (var inputStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) { DirectoryInfo singleRootDirectory = GetSingleRootDirectory(inputStream); inputStream.Position = 0; // Needs resetting after GetSingleRootDirectory() var tarInputStream = new TarInputStream(inputStream); TarEntry tarEntry; while ((tarEntry = tarInputStream.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } string name = tarEntry.Name.Replace('/', Path.DirectorySeparatorChar); if (singleRootDirectory != null) { name = name.Substring(singleRootDirectory.Name.Length); } if (Path.IsPathRooted(name)) { name = name.Substring(Path.GetPathRoot(name).Length); } string fullName = Path.Combine(targetDirectory.FullName, name); string directoryName = Path.GetDirectoryName(fullName); if (directoryName != null) { Directory.CreateDirectory(directoryName); } var outputStream = new FileStream(fullName, FileMode.Create); tarInputStream.CopyEntryContents(outputStream); outputStream.Close(); DateTime dateTime = DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc); File.SetLastWriteTime(fullName, dateTime); } tarInputStream.Close(); } _log.Debug($"Extracted tar file: {file} to folder {targetDirectory}", file.FullName, targetDirectory.FullName); }
public override IEnumerable <VirtualPath> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) { using (FileStream fsIn = new FileStream(_tarFilename, FileMode.Open, FileAccess.Read)) { TarInputStream tarIn = new TarInputStream(fsIn); TarEntry tarEntry; while ((tarEntry = tarIn.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { yield return(new TarPath(this, tarEntry.File)); } } tarIn.Close(); } }
private bool DownloadArchive(string expectedCommit) { var tDownload = client.Repository.Content.GetArchive(username, repository); var bArchive = tDownload.Result; var stream = new MemoryStream(bArchive); Stream gzipStream = new GZipInputStream(stream); Stream gzipStream2 = new GZipInputStream(stream); TarInputStream tarIn = new TarInputStream(gzipStream); TarEntry tarEntry; var strRoot = ""; while ((tarEntry = tarIn.GetNextEntry()) != null) { string name = tarEntry.Name.Replace('/', Path.DirectorySeparatorChar); if (strRoot == "") { strRoot = name; if (!strRoot.Contains(expectedCommit)) { return(false); } } if (tarEntry.IsDirectory) { continue; } if (Path.IsPathRooted(name)) { name = name.Substring(Path.GetPathRoot(name).Length); } name = name.Replace(strRoot, ""); string outName = Path.Combine(output, name); string directoryName = Path.GetDirectoryName(outName); Directory.CreateDirectory(directoryName); FileStream outStr = new FileStream(outName, System.IO.FileMode.Create); tarIn.CopyEntryContents(outStr); outStr.Close(); } tarIn.Close(); gzipStream.Close(); stream.Close(); return(true); }
public void ExtractTarFile() { try { using (var inputStream = System.IO.File.OpenRead(FullEpgPackagePath)) using (var tarStream = new TarInputStream(inputStream, Encoding.UTF8)) { ProcessTarInputStream(tarStream); OperationsSuccessful = System.IO.File.Exists(OutputEpgFile); tarStream.Close(); inputStream.Close(); } } catch (Exception etfException) { Console.WriteLine(etfException); throw; } }
private void ExtractTarByEntry(string tarFileName, string targetDir) { using (FileStream fsIn = new FileStream(tarFileName, FileMode.Open, FileAccess.Read)) { TarInputStream tarIn = new TarInputStream(fsIn); TarEntry tarEntry; while ((tarEntry = tarIn.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } // Converts the unix forward slashes in the filenames to windows backslashes // string name = tarEntry.Name.Replace('/', Path.DirectorySeparatorChar); // Remove any root e.g. '\' because a PathRooted filename defeats Path.Combine if (Path.IsPathRooted(name)) { name = name.Substring(Path.GetPathRoot(name).Length); } // Apply further name transformations here as necessary string outName = Path.Combine(targetDir, name); string directoryName = Path.GetDirectoryName(outName); Directory.CreateDirectory(directoryName); FileStream outStr = new FileStream(outName, FileMode.Create); tarIn.CopyEntryContents(outStr); outStr.Close(); // Set the modification date/time. This approach seems to solve timezone issues. DateTime myDt = DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc); File.SetLastWriteTime(outName, myDt); } tarIn.Close(); } }
private static Dictionary <String, Byte[]> UnzipToMemory(Stream originalZipStream) { var result = new Dictionary <string, Byte[]>(); using (var stream = new MemoryStream()) { Stream gzipStream = new GZipInputStream(originalZipStream); TarInputStream tarStream = new TarInputStream(gzipStream); TarEntry tarEntry; while ((tarEntry = tarStream.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } string name = tarEntry.Name.Replace('/', Path.DirectorySeparatorChar); if (!name.EndsWith(".xml")) { continue; } if (Path.IsPathRooted(name)) { name = name.Substring(Path.GetPathRoot(name).Length); } using (var contentStream = new MemoryStream()) { tarStream.CopyEntryContents(contentStream); result.Add(name.ToLower(), contentStream.ToArray()); } } tarStream.Close(); } return(result); }
public static long ReadFileOrDirectoryFromStream(Stream stream, string pathToWrite, bool overwrite = true, bool closeStreamWhenComplete = true) { var tar = new TarInputStream(stream); tar.IsStreamOwner = closeStreamWhenComplete; long bytesRead = 0; // we can't use the simple ExtractContents because we need to be overwrite aware, // so we iterate instead TarEntry entry; while ((entry = tar.GetNextEntry()) != null) { var extractPath = Path.Combine(pathToWrite, entry.Name); if (entry.IsDirectory) { // we don't have to worry about writing over directories Directory.CreateDirectory(extractPath); } else { // if overwrite is on, use Create FileMode. If not, use CreateNew, which will throw // an IO error if the file already exists. using (var fs = new FileStream(extractPath, overwrite ? FileMode.Create : FileMode.CreateNew)) { tar.CopyEntryContents(fs); bytesRead += entry.Size; } } } tar.Close(); return(bytesRead); }
/// <summary> /// Decompress the source file containing the categories and the content of the blacklisted sites. /// </summary> /// <returns>True if decompressing process success efectively, otherwise false.</returns> private bool decompressSourceFile() { // Set the currentOperation to "decompressingSourceFile" clsSettings.serviceSettings.currentOperation = operationList.decompressingSourceFile; bool result = false; // Form the FileInfo variable with the file to decompress. FileInfo fileInfo = new FileInfo(string.Format("{0}{1}", clsSettings.serviceSettings.dataDirectory, clsSettings.serviceSettings.downloadedFileName)); if (!fileInfo.Exists) { clsSettings.serviceSettings.currentOperation = operationList.waitingForNextExecution; clsLogProcessing.WriteToEventLog(string.Format("El estado de operaciones ha cambiado a \"{0}\", porque durante la " + "operación \"{1}\" no se encontró el recurso (fichero) \"{2}\" como se esperaba, para ejecutar la descompresión " + "del mismo. Si esta es la primera vez que observa este error no se requiere intervención alguna por parte del usuario. " + "El sistema se encargará de procesar todas las operaciones desde el principio para obtener el fichero correspondiente.", operationList.waitingForNextExecution, operationList.decompressingSourceFile, fileInfo.FullName), EventLogEntryType.Error); return(false); } Stream inStream = File.OpenRead(fileInfo.FullName); // Extract try { // Extract TAR, GZipped File. TarArchive tarGZippedArchive = TarArchive.CreateInputTarArchive(new GZipStream(inStream, CompressionMode.Decompress)); tarGZippedArchive.ExtractContents(clsSettings.serviceSettings.dataDirectory.FullName); // Do some cleanup. tarGZippedArchive.Close(); if (tarGZippedArchive != null) { tarGZippedArchive = null; } result = true; } catch (System.Exception) { // Sometimes the file is opened weith decompressing software (sach as WinRar) and from that momento it's not a GZipped file anymore. // Extract TAR File /* THIS DOES NOT WORK. * TarArchive tarArchive = TarArchive.CreateInputTarArchive(inStream); * tarArchive.ExtractContents(clsSettings.serviceSettings.dataDirectory.FullName); * tarArchive.Close(); */ using (FileStream fsIn = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read)) { // The TarInputStream reads a UNIX tar archive as an InputStream. TarInputStream tarIn = new TarInputStream(fsIn); TarEntry tarEntry; while ((tarEntry = tarIn.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } // Converts the unix forward slashes in the filenames to windows backslashes. string name = tarEntry.Name.Replace('/', Path.DirectorySeparatorChar); // Apply further name transformations here as necessary string outName = Path.Combine(clsSettings.serviceSettings.dataDirectory.FullName, name); string directoryName = Path.GetDirectoryName(outName); Directory.CreateDirectory(directoryName); FileStream outStr = new FileStream(outName, FileMode.Create); tarIn.CopyEntryContents(outStr); // Do some cleanup. outStr.Close(); if (outStr != null) { outStr = null; } } // Do some cleanup. if (tarIn != null) { tarIn.Close(); tarIn = null; } if (fsIn != null) { fsIn.Close(); } } result = true; } finally { if (inStream != null) { inStream.Close(); inStream = null; } } return(result); }
private static void ExtractTarByEntry(Stream inputStream, string targetDir, bool asciiTranslate, Action <long, long> progress) { TarInputStream tarIn = new TarInputStream(inputStream); TarEntry tarEntry; while ((tarEntry = tarIn.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } progress(tarIn.Position, tarIn.Length); // Converts the unix forward slashes in the filenames to windows backslashes string name = tarEntry.Name.Replace('/', Path.DirectorySeparatorChar); // Remove any root e.g. '\' because a PathRooted filename defeats Path.Combine if (Path.IsPathRooted(name)) { name = name.Substring(Path.GetPathRoot(name).Length); } // Apply further name transformations here as necessary string outName = Path.Combine(targetDir, name).NormalizePath(); string directoryName = Path.GetDirectoryName(outName); // Does nothing if directory exists Directory.CreateDirectory(directoryName); if (tarEntry.TarHeader.TypeFlag != '0') { switch ((char)tarEntry.TarHeader.TypeFlag) { case '1': if (Platform.PlatformIdentifier == Platforms.PlatformID.Win32NT) { Platform.CreateHardLinkWin32(outName.NormalizePath(), Path.Combine(targetDir, tarEntry.TarHeader.LinkName).NormalizePath(), !tarEntry.IsDirectory); } else { var symLinkInfo = new UnixSymbolicLinkInfo(Path.Combine(targetDir, tarEntry.TarHeader.LinkName).NormalizePath()); symLinkInfo.CreateLink(outName); } break; case '2': if (Platform.PlatformIdentifier == Platforms.PlatformID.Win32NT) { Platform.CreateSymbolicLinkWin32(outName.NormalizePath(), tarEntry.TarHeader.LinkName, !tarEntry.IsDirectory); } else { var symLinkInfo = new UnixSymbolicLinkInfo(outName.NormalizePath()); symLinkInfo.CreateSymbolicLinkTo(tarEntry.TarHeader.LinkName); } break; } } else { try { using (var outStr = new FileStream(outName, FileMode.Create)) { if (asciiTranslate) { CopyWithAsciiTranslate(tarIn, outStr); } else { tarIn.CopyEntryContents(outStr); } } if (Platform.PlatformIdentifier == Platforms.PlatformID.Unix || Platform.PlatformIdentifier == Platforms.PlatformID.MacOSX) { var unixFileInfo = new UnixFileInfo(outName) { FileAccessPermissions = (FileAccessPermissions)tarEntry.TarHeader.Mode }; } // Set the modification date/time. This approach seems to solve timezone issues. DateTime myDt = DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc); File.SetLastWriteTime(outName, myDt); } catch (Exception) { } } } tarIn.Close(); }
static public string unTarFile(string TargetFile, string fileDir) { string rootFile = ""; try { //读取压缩文件(zip文件),准备解压缩 TarInputStream s = new TarInputStream(File.OpenRead(TargetFile.Trim())); TarEntry theEntry; //解压出来的文件保存的路径 string rootDir = " "; //根目录下的第一个子文件夹的名称 while ((theEntry = s.GetNextEntry()) != null) { string temp = theEntry.Name.PathFilter(); rootDir = Path.GetDirectoryName(temp); //得到根目录下的第一级子文件夹的名称 if (rootDir.IndexOf("\\") >= 0) { rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1); } string dir = Path.GetDirectoryName(temp); //根目录下的第一级子文件夹的下的文件夹的名称 string fileName = Path.GetFileName(temp); //根目录下的文件名称 if (dir != " " && dir != "") //创建根目录下的子文件夹,不限制级别 { if (!Directory.Exists(fileDir + "\\" + dir)) { //在指定的路径创建文件夹 Directory.CreateDirectory(fileDir + "\\" + dir); } } //以下为解压缩zip文件的基本步骤 //基本思路就是遍历压缩文件里的所有文件,创建一个相同的文件。 if (fileName != String.Empty) { FileStream streamWriter = File.Create(fileDir + "\\" + temp); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } s.Close(); return(rootFile); } catch (Exception ex) { return("1; " + ex.Message); } }
private static void ParseTAR(TarDirectory root, TarInputStream input, string fullPath) { Dictionary <string, byte[]> dictionary = new Dictionary <string, byte[]>(); List <TarEntry> list = new List <TarEntry>(); List <TarDirectory> list2 = new List <TarDirectory>(); byte[] buffer = new byte[16384]; try { using (MemoryStream memoryStream = new MemoryStream()) { TarEntry nextEntry; while ((nextEntry = input.GetNextEntry()) != null) { ReadTarEntryData(input, memoryStream, buffer); dictionary.Add(nextEntry.Name, memoryStream.ToArray()); list.Add(nextEntry); memoryStream.Position = 0L; memoryStream.SetLength(0L); } } list2.Add(root); foreach (TarEntry item in list.Where((TarEntry e) => e.IsDirectory && !string.IsNullOrEmpty(e.Name))) { string str = FormatFolderPath(item.Name); list2.Add(new TarDirectory(fullPath + "/" + str, str)); } foreach (TarEntry item2 in list.Where((TarEntry e) => !e.IsDirectory)) { string b = FormatFolderPath(Path.GetDirectoryName(item2.Name)); TarDirectory tarDirectory = null; foreach (TarDirectory item3 in list2) { if (item3.inArchiveFullPath == b) { tarDirectory = item3; break; } } tarDirectory.files.Add(new TarFile(dictionary[item2.Name], fullPath + "/" + item2.Name, Path.GetFileName(item2.Name))); } foreach (TarDirectory item4 in list2) { if (string.IsNullOrEmpty(item4.inArchiveFullPath)) { continue; } string b2 = FormatFolderPath(Path.GetDirectoryName(item4.inArchiveFullPath)); TarDirectory tarDirectory2 = null; foreach (TarDirectory item5 in list2) { if (item5.inArchiveFullPath == b2) { tarDirectory2 = item5; break; } } tarDirectory2.subDirectories.Add(item4); } } finally { input.Close(); } }
bool _Extract(string backup, string outputDirecory) { try { var tarPAth = $"{backup}.tar.gz"; if (File.Exists(tarPAth)) { File.Delete(tarPAth); } var outStream = File.Open(tarPAth, FileMode.OpenOrCreate); foreach (var b in BackupManager.TarHeader) { outStream.WriteByte(b); } var fileStream = File.OpenRead(backup); fileStream.Position = 24; fileStream.CopyTo(outStream); fileStream.Close(); outStream.Position = 0; //TarArchive tarArchive = TarArchive.CreateInputTarArchive(outStream); //tarArchive.ExtractContents(AdbManager.tempDirectory); //tarArchive.Close(); var targetDir = AdbManager.tempDirectory; using (var fsIn = new GZipInputStream(outStream)) { TarInputStream tarIn = new TarInputStream(fsIn); TarEntry tarEntry; try { while ((tarEntry = tarIn.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } // Converts the unix forward slashes in the filenames to windows backslashes string name = tarEntry.Name.Replace('/', Path.DirectorySeparatorChar); if (name.Contains(":")) { continue; } // Remove any root e.g. '\' because a PathRooted filename defeats Path.Combine if (Path.IsPathRooted(name)) { name = name.Substring(Path.GetPathRoot(name).Length); } // Apply further name transformations here as necessary string outName = Path.Combine(targetDir, name); string directoryName = Path.GetDirectoryName(outName); //if (!directoryName.Contains("SaveGames")) // continue; // Does nothing if directory exists Directory.CreateDirectory(directoryName); FileStream outStr = new FileStream(outName, FileMode.Create); //if (asciiTranslate) // CopyWithAsciiTranslate(tarIn, outStr); //else tarIn.CopyEntryContents(outStr); outStr.Close(); // Set the modification date/time. This approach seems to solve timezone issues. DateTime myDt = DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc); File.SetLastWriteTime(outName, myDt); } } catch (EndOfStreamException) { } tarIn.Close(); } outStream.Close(); return(true); } catch { } return(false); }
public void UpdateTar(string tarFileName, string targetFile, bool asciiTranslate) { using (FileStream fsIn = new FileStream(tarFileName, FileMode.Open, FileAccess.Read)) { string tmpTar = Path.Combine(Path.GetDirectoryName(tarFileName), "tmp.tar"); using (FileStream fsOut = new FileStream(tmpTar, FileMode.OpenOrCreate, FileAccess.Write)) { TarOutputStream tarOutputStream = new TarOutputStream(fsOut); TarInputStream tarIn = new TarInputStream(fsIn); TarEntry tarEntry; while ((tarEntry = tarIn.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } // Converts the unix forward slashes in the filenames to windows backslashes // string name = tarEntry.Name.Replace('/', Path.DirectorySeparatorChar); string sourceFileName = Path.GetFileName(targetFile); string targetFileName = Path.GetFileName(tarEntry.Name); if (sourceFileName.Equals(targetFileName)) { using (Stream inputStream = File.OpenRead(targetFile)) { long fileSize = inputStream.Length; TarEntry entry = TarEntry.CreateTarEntry(tarEntry.Name); // Must set size, otherwise TarOutputStream will fail when output exceeds. entry.Size = fileSize; // Add the entry to the tar stream, before writing the data. tarOutputStream.PutNextEntry(entry); // this is copied from TarArchive.WriteEntryCore byte[] localBuffer = new byte[32 * 1024]; while (true) { int numRead = inputStream.Read(localBuffer, 0, localBuffer.Length); if (numRead <= 0) { break; } tarOutputStream.Write(localBuffer, 0, numRead); } } tarOutputStream.CloseEntry(); } else { tarOutputStream.PutNextEntry(tarEntry); if (asciiTranslate) { CopyWithAsciiTranslate(tarIn, tarOutputStream); } else { tarIn.CopyEntryContents(tarOutputStream); } tarOutputStream.CloseEntry(); } } tarIn.Close(); tarOutputStream.Close(); } File.Delete(tarFileName); File.Move(tmpTar, tarFileName); } }
/// <summary> /// Metoda, ki se pokliče, ko kliknemo na gumb Razširi. Odpre saveFileDialog in prebere kam bomo datoteko /// shranili. /// OPOMBA: metoda še ne deluje 100% pravilno. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnExtract_Click(object sender, EventArgs e) { filesList = new StringCollection(); FolderBrowserDialog fbd = new FolderBrowserDialog(); if (fileExplorer.SelectedItems.Count > 0 && fbd.ShowDialog() == DialogResult.OK) { // Pridobi shranjevalno pot string savePath = fbd.SelectedPath; foreach (ListViewItem item in fileExplorer.SelectedItems) { string file = item.SubItems[0].Text; // Preveri katera oblika datoteke je: ZIP, TAR, GZIP ali TAR.BZ2 if (Path.GetExtension(txtPath.Text) == ".zip") { ZipFile zip = Ionic.Zip.ZipFile.Read(txtPath.Text); ZipEntry entry = zip[file]; if (zip[file].UsesEncryption == true) { PasswordPrompt passWin = new PasswordPrompt(); passWin.ShowDialog(); zip.Password = passWin.pass; try { entry.ExtractWithPassword(savePath, passWin.pass); } catch (BadPasswordException) { if (MessageBox.Show("Napačno geslo", "Napaka", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry) { passWin.ShowDialog(); } } } string enExists = savePath + @"\" + entry.FileName; if (File.Exists(enExists)) { if (MessageBox.Show("Datoteka " + file + " že obstaja. Ali jo želite zamenjati?", "Datoteka obstaja", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { entry.Extract(savePath, ExtractExistingFileAction.OverwriteSilently); } else { break; } } else { entry.Extract(savePath); } } else if (Path.GetExtension(txtPath.Text) == ".tar") { byte[] outBuffer = new byte[4096]; TarInputStream tar = new TarInputStream(new FileStream(txtPath.Text, FileMode.Open, FileAccess.Read)); TarEntry curEntry = tar.GetNextEntry(); while (curEntry != null) { if (curEntry.Name == file) { FileStream fs = new FileStream(savePath + @"\" + curEntry.Name, FileMode.Create, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fs); tar.Read(outBuffer, 0, (int)curEntry.Size); bw.Write(outBuffer, 0, outBuffer.Length); bw.Close(); } curEntry = tar.GetNextEntry(); } tar.Close(); } else if (Path.GetExtension(txtPath.Text) == ".bz2") { Stream str = new FileStream(txtPath.Text, FileMode.Open, FileAccess.Read); BZip2InputStream bzStr = new BZip2InputStream(str); TarInputStream tar = new TarInputStream(bzStr); TarEntry curEntry = tar.GetNextEntry(); while (curEntry != null) { if (curEntry.Name == file) { byte[] outBuffer = new byte[curEntry.Size]; FileStream fs = new FileStream(savePath + @"\" + curEntry.Name, FileMode.Create, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fs); tar.Read(outBuffer, 0, (int)curEntry.Size); bw.Write(outBuffer, 0, outBuffer.Length); bw.Close(); } curEntry = tar.GetNextEntry(); } tar.Close(); } else if (Path.GetExtension(txtPath.Text) == ".tgz") { Stream str = new FileStream(txtPath.Text, FileMode.Open, FileAccess.Read); GZipInputStream gzStr = new GZipInputStream(str); TarInputStream tar = new TarInputStream(gzStr); TarEntry curEntry = tar.GetNextEntry(); while (curEntry != null) { if (curEntry.Name == file) { byte[] outBuffer = new byte[curEntry.Size]; FileStream fs = new FileStream(savePath + @"\" + curEntry.Name, FileMode.Create, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fs); tar.Read(outBuffer, 0, (int)curEntry.Size); bw.Write(outBuffer, 0, outBuffer.Length); bw.Close(); } curEntry = tar.GetNextEntry(); } tar.Close(); } } } else { MessageBox.Show("Nobena datoteka ni bila izbrana. Prosimo izberite datoteke.", "Napaka", MessageBoxButtons.OK, MessageBoxIcon.Information); } }