2017-03-06 84 views
0

我在一個.tar.gz存檔文件中有一些文件。這些文件位於Linux服務器上。如果我知道它是名稱,如何從此歸檔中的特定文件讀取? 對於從txt文件直接讀取,我用下面的代碼:Asp .NET從tar.gz存檔中讀取文件

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

它可以讀取該文件而不復制在本地計算機上的存檔,像上面的代碼?

+0

我不認爲認爲焦油球像壓縮文件一樣工作,你必須下載文件,然後解壓縮它,以獲得我想它的TXT文件。 – War

+0

我試過和這個解決方案。使用下面的代碼,我將存檔(gz)從服務器下載到本地,解壓tar文件,但我無法知道如何從此存檔提取一個特定文件。 –

+0

'WebClient wc = new WebClient(){Credentials = cred}; wc.DownloadFile(path,gzFile.FullName); 使用(的FileStream INFILE = gzFile.OpenRead()){ 使用 (的FileStream tarFileStream = File.Create(tarFile.FullName)) { 使用(GZipStream decompStreem =新GZipStream(infile中,CompressionMode.Decompress)) decompStreem.CopyTo(tarFileStream); }} }' –

回答

0

我找到了解決方案。也許這可以幫助你們。

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