2016-12-28 10 views
0
request = MakeConnection(uri, WebRequestMethods.Ftp.DownloadFile, username, password); 
response = (FtpWebResponse)request.GetResponse(); 
Stream responseStream = response.GetResponseStream(); 

//This part of the code is used to write the read content from the server 
using (StreamReader responseReader = new StreamReader(responseStream)) 
{ 
    using (var destinationStream = new FileStream(toFilenameToWrite, FileMode.Create)) 
    { 
     byte[] fileContents = Encoding.UTF8.GetBytes(responseReader.ReadToEnd()); 
     destinationStream.Write(fileContents, 0, fileContents.Length); 
    } 
} 
//This part of the code is used to write the read content from the server 
using (var destinationStream = new FileStream(toFilenameToWrite, FileMode.Create)) 
{ 
    long length = response.ContentLength; 
    int bufferSize = 2048; 
    int readCount; 
    byte[] buffer = new byte[2048]; 
    readCount = responseStream.Read(buffer, 0, bufferSize); 
    while (readCount > 0) 
    { 
     destinationStream.Write(buffer, 0, readCount); 
     readCount = responseStream.Read(buffer, 0, bufferSize); 
    } 
} 

прежних записывает содержимое в файл, но при попытке открыть файл, он говорит, что он поврежден. Но более поздняя работа отлично работает при загрузке zip-файлов. Есть ли какая-то конкретная причина, почему прежний код не работает для zip-файлов, так как он отлично работает для текстовых файлов?Zip файл поврежденные после загрузки с сервера в C#

+0

StreamReader является TextReader. См. [Этот ответ] (http://stackoverflow.com/a/4769070/60761). –

ответ

0

Используйте BinaryWriter и передайте его FileStream.

//This part of the code is used to write the read content from the server 
    using (var destinationStream = new BinaryWriter(new FileStream(toFilenameToWrite, FileMode.Create))) 
    { 
     long length = response.ContentLength; 
     int bufferSize = 2048; 
     int readCount; 
     byte[] buffer = new byte[2048]; 
     readCount = responseStream.Read(buffer, 0, bufferSize); 
     while (readCount > 0) 
     { 
      destinationStream.Write(buffer, 0, readCount); 
      readCount = responseStream.Read(buffer, 0, bufferSize); 
     } 
    } 
+0

Я пробовал, но результат такой же – Prabu

+0

zip все еще коррумпирован? – Nino

+0

Да, файл все еще поврежден – Prabu

2
byte[] fileContents = Encoding.UTF8.GetBytes(responseReader.ReadToEnd()); 

Вы пытаетесь интерпретировать бинарный файл PDF как UTF-8 строк текста. Это просто не может работать.

Для получения точного кода см. Upload and download a binary file to/from FTP server in C#/.NET.

+0

Я полностью забыл об этом ... но второй метод должен работать (при использовании BinaryWriter для записи потока) – Nino

+0

Я понял, что ваш второй код работает (* «Но тот, кто делает это отлично, когда загружает zip-файлы» *). Не так ли? –

+0

Да, тот, который позже загружается отлично. – Prabu

0

вот мое решение, которое работало для меня

C#

public IActionResult GetZip([FromBody] List<DocumentAndSourceDto> documents) 
{ 
    List<Document> listOfDocuments = new List<Document>(); 

    foreach (DocumentAndSourceDto doc in documents) 
     listOfDocuments.Add(_documentService.GetDocumentWithServerPath(doc.Id)); 

    using (var ms = new MemoryStream()) 
    { 
     using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true)) 
     { 
      foreach (var attachment in listOfDocuments) 
      { 
       var entry = zipArchive.CreateEntry(attachment.FileName); 

       using (var fileStream = new FileStream(attachment.FilePath, FileMode.Open)) 
       using (var entryStream = entry.Open()) 
       { 
        fileStream.CopyTo(entryStream); 
       } 
      } 

     } 
     ms.Position = 0; 
     return File(ms.ToArray(), "application/zip"); 
    } 

    throw new ErrorException("Can't zip files"); 
} 

не пропустите ms.Position = 0; здесь