2017-10-11 40 views
2

嘿傢伙我的問題是標題。我曾經嘗試這樣做:壓縮一個目錄並上傳到FTP服務器,而無需在本地保存.zip文件在C#

public void UploadToFtp(List<strucProduktdaten> ProductData) 
{ 
    ProductData.ForEach(delegate(strucProduktdaten data) 
    { 
     ZipFile.CreateFromDirectory(data.Quellpfad, data.Zielpfad, CompressionLevel.Fastest, true); 
    }); 
} 


static void Main(string[] args) 
{ 
    List<strucProduktdaten> ProductDataList = new List<strucProduktdaten>(); 
    strucProduktdaten ProduktData = new strucProduktdaten(); 
    ProduktData.Quellpfad = @"Path\to\zip"; 
    ProduktData.Zielpfad = @"Link to the ftp"; // <- i know the link makes no sense without a connect to the ftp with uname and password 

    ProductDataList.Add(ProduktData); 

    ftpClient.UploadToFtp(ProductDataList); 
} 

錯誤:

System.NotSupportedException:"The Path format is not supported."

我不知道我應該如何在這種情況下,FTP服務器連接並荏苒RAM中的目錄,並直接發送到服務器。

...有人可以幫助或有鏈接到類似或平等的問題什麼解決?

+1

看看這個:https://stackoverflow.com/q/17232414/616304 –

+0

感謝,這將有助於我 – ARX

回答

1

像這樣的工作,儘可能獲取ZIP到內存中去:

public static byte[] ZipFolderToMemory(string folder) 
{ 
    using (var stream = new MemoryStream()) 
    { 
     using (var archive = new ZipArchive(stream, ZipArchiveMode.Create)) 
     { 
      foreach (var filePath in Directory.EnumerateFiles(folder)) 
      { 
       var entry = archive.CreateEntry(Path.GetFileName(filePath)); 

       using (var zipEntry = entry.Open()) 
       using (var file = new FileStream(filePath, FileMode.Open)) 
       { 
        file.CopyTo(zipEntry); 
       } 
      } 
     } 

     return stream.ToArray(); 
    } 
} 

一旦你的字節數組,你應該能夠很容易地將其發送到服務器。

+0

謝謝你正在工作 – ARX

1

創建MemoryStream中的ZIP存檔並上傳它。

using (Stream memoryStream = new MemoryStream()) 
{ 
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) 
    { 
     foreach (string path in Directory.EnumerateFiles(@"C:\source\directory")) 
     { 
      ZipArchiveEntry entry = archive.CreateEntry(Path.GetFileName(path)); 

      using (Stream entryStream = entry.Open()) 
      using (Stream fileStream = File.OpenRead(path)) 
      { 
       fileStream.CopyTo(entryStream); 
      } 
     } 
    } 

    memoryStream.Seek(0, SeekOrigin.Begin); 

    FtpWebRequest request = 
     (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/archive.zip"); 
    request.Credentials = new NetworkCredential("username", "password"); 
    request.Method = WebRequestMethods.Ftp.UploadFile; 
    using (Stream ftpStream = request.GetRequestStream()) 
    { 
     memoryStream.CopyTo(ftpStream); 
    } 
} 

不幸的是,ZipArchive需要一個可查找的流。如果沒有,您可以直接寫入FTP請求流,而不需要將整個ZIP文件保存在內存中。基於


+0

謝謝你,這正是我搜索和工作得很好! – ARX

+0

不客氣。雖然在堆棧溢出,我們感謝[接受答案](// stackoverflow.com/help/someone-answers)。 –

相關問題