【问题标题】:Asp .NET Read a file from a tar.gz archiveAsp .NET 从 tar.gz 存档中读取文件
【发布时间】:2017-07-26 08:03:37
【问题描述】:

我在一个 .tar.gz 存档中有一些文件。这些文件位于 linux 服务器上。如果我知道它的名称,如何从该存档中的特定文件中读取它? 为了直接从 txt 文件中读取,我使用了以下代码:

Uri urlFile = new Uri("ftp://" + ServerName + "/%2f" + FilePath + "/" + fileName);
WebClient req = new WebClient() { Credentials=new NetworkCredential("user","psw")};
string result = req.DownloadString(urlFile);

是否可以在不复制本地计算机上的存档的情况下读取此文件,类似于上面的代码?

【问题讨论】:

  • 我认为 tar 球不像 zip 文件那样工作,你必须下载文件然后解压缩才能从中获取 txt 文件。
  • 我试过这个解决方案。使用以下代码,我将存档(gz)从服务器下载到本地,提取 tar 文件,但我不知道如何从该存档中提取一个特定文件。
  • WebClient wc = new WebClient() { Credentials = cred }; wc.DownloadFile(path, gzFile.FullName); using (FileStream inFile = gzFile.OpenRead()) { using (FileStream tarFileStream = File.Create(tarFile.FullName)) { using (GZipStream decompStreem = new GZipStream(inFile, CompressionMode.Decompress)) { decompStreem.CopyTo(tarFileStream); } } }
  • 我认为不可能从存档中提取单个文件...我认为您必须将整个存档提取到一个文件夹然后读取您想要的文件
  • 我成功地从这个存档中提取所有文件并在阅读后将其删除(使用ICSharpCode.SharpZipLib library),但我认为这不是一个好的解决方案。如果两个用户尝试同时读取此文件,则一个用户可以在第二个用户读取文件之前删除文件。

标签: c# asp.net archive tar


【解决方案1】:

我找到了解决方案。也许这对你们有帮助。

// archivePath="ftp://myLinuxServer.com/%2f/move/files/archive/20170225.tar.gz";
    public static string ExtractFileFromArchive(string archivePath, string fileName)
    {
        string stringFromFile="File not found";
        WebClient wc = new WebClient() { Credentials = cred, Proxy= webProxy  };        //Create webClient with all necessary settings 

        using (Stream source = new GZipInputStream(wc.OpenRead(archivePath)))  //wc.OpenRead() create one stream with archive tar.gz from our server
        {
            using (TarInputStream tarStr =new TarInputStream(source))   //TarInputStream is a stream from ICSharpCode.SharpZipLib.Tar library(need install SharpZipLib in nutgets)
            {
                TarEntry te;
                while ((te = tarStr.GetNextEntry())!=null)  // Go through all files from archive
                {
                    if (te.Name == fileName)
                    {
                        using (Stream fs = new MemoryStream())  //Create a empty stream that we will be fill with file contents.
                        {
                            tarStr.CopyEntryContents(fs);
                            fs.Position = 0;                    //Move stream position to 0, in order to read from beginning
                            stringFromFile = new StreamReader(fs).ReadToEnd(); //Convert stream to string
                        }
                        break;
                    }
                }
            }
        }

        return stringFromFile;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2015-09-06
    相关资源
    最近更新 更多