2014-06-24 1 views
1

아래 코드는 내가 사용하고있는 코드입니다. 기본적으로 배열을 반복하고 파일을 zip에 추가 한 다음 zip을 메모리 스트림에 저장 한 다음 첨부 파일을 전자 메일로 보냅니다.C# Zip Zip에 바이트 [] 저장, 스트림으로 변환, 메일 첨부 파일로 메일 전송 - 첨부 파일에 대한 적절한 방법

디버그에서 항목을 보면 zipfile에 약 20MB의 데이터가 있음을 알 수 있습니다. 첨부 파일을받을 때 약 230 비트의 데이터 만 있고 내용이 없습니다. 이견있는 사람? 나는 그것이의 크기가 첨부 볼 -1 그래서 무슨 적절한 방법이 항목을 첨부하면

byteCount = byteCount + docs[holder].FileSize; 
      if (byteCount > byteLimit) 
      { 
       //create a new stream and save the stream to the zip file 
       System.IO.MemoryStream attachmentstream = new System.IO.MemoryStream(); 
       zip.Save(attachmentstream); 

       //create the attachment and send that attachment to the mail 
       Attachment data = new Attachment(attachmentstream, "documentrequest.zip"); 
       theMailMessage.Attachments.Add(data); 

       //send Mail 
       SmtpClient theClient = new SmtpClient("mymail"); 
       theClient.UseDefaultCredentials = false; 
       System.Net.NetworkCredential theCredential = new System.Net.NetworkCredential("bytebte", "2323232"); 
       theClient.Credentials = theCredential; 
       theClient.Send(theMailMessage); 
       zip = new ZipFile(); 

       //iterate Document Holder 
       holder++; 
      } 
      else 
      { 
       //create the stream and add it to the zip file 
       //System.IO.MemoryStream stream = new System.IO.MemoryStream(docs[holder].FileData); 
       zip.AddEntry("DocId_"+docs[holder].DocumentId+"_"+docs[holder].FileName, docs[holder].FileData); 
       holder++; 

      } 

문제는 여기 Attachment data = new Attachment(attachmentstream, "documentrequest.zip");입니까?

+1

'zip.Save'를 호출하면 첨부 파일 스트림이 닫히고 데이터가 손실 될 수 있습니다. 어떤 Zip 라이브러리를 사용하고 있습니까? –

+0

여기서 가장 중요한 소프트웨어 ('zip.')는 식별되지 않습니다. –

+0

Jim의 답변 외에도 (지금까지이 문제를 제기했을지라도 이것은 다른 독자에게 더 유용 할 것입니다.) 단순히 스트림의 위치를 ​​재설정 할 수 있습니다. 이렇게 : http://stackoverflow.com/a/2267750/722393. – InteXX

답변

2

zip.Save에 대한 호출이 작성된 후 스트림을 닫는 것으로 의심됩니다. 결국 바이트를 배열에 복사 한 다음 읽을 수있는 새로운 MemoryStream을 생성해야합니다. 예 :

//create a new stream and save the stream to the zip file 
byte[] streamBytes; 
using (var ms = new MemoryStream()) 
{ 
    zip.Save(ms); 
    // copy the bytes 
    streamBytes = ms.ToArray(); 
} 

// create a stream for the attachment 
using (var attachmentStream = new MemoryStream(streamBytes)) 
{ 
    //create the attachment and send that attachment to the mail 
    Attachment data = new Attachment(attachmentstream, "documentrequest.zip"); 
    theMailMessage.Attachments.Add(data); 

    // rest of your code here 
} 
+0

짐 나는 줄에서 볼 수있다 첨부 자료 = 새로운 첨부 자료 (attachmentstream, "documentrequest.zip"); attachmentstream은 여전히 ​​정확한 크기이지만 첨부 파일의 크기는 -1입니다. –

+0

Jim - 추천 내용이 실제로 스트림을 닫은 다음 메일을 보낼 수 없습니다. –

+0

닫힌 스트림에 대한 위의 설명을 무시하지만 그래도 여전히 잘못된 파일입니다. –

관련 문제