Asp .NET从tar.gz存档中读取文件

时间:2017-03-06 12:35:57

标签: c# asp.net archive tar

我在一个.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);

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

1 个答案:

答案 0 :(得分:2)

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

// 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;
    }