2010-01-29 6 views
7

프로젝트에는 blob로 SQL Server db에 저장된 파일이 있습니다. 데이터베이스에서 파일을 가져 와서 디스크에 쓰지 않고 여러 파일을 전자 메일에 첨부하고 싶습니다. 디스크에 쓰지 않고도 프로그램에 여러 파일을 첨부 할 수 있습니다.

는 (모든 첨부 파일 없음으로, 작동 확인) 내가 지금까지 무엇을 가지고 :

exception message: Failure sending mail. 
source: System 
stack trace: 
    at System.Net.Mail.SmtpClient.Send(MailMessage message) 
    at MyCompany.Shared.Email.SMTPMessage.SendMessage(String to, String from, String cc, String bcc, String subject, String body, Boolean IsHtml, List`1 attachments) in C:\svn_repos\branches\2010.02.28\Net\Common\Shared\Email\SMTPMessage.cs:line 116 

inner exception msg: Cannot access a closed Stream. 
inner source: mscorlib 
inner targetsite: {Void StreamIsClosed()} 
inner stack trace: 
    at System.IO.__Error.StreamIsClosed() 
    at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count) 
    at System.Net.Mime.MimePart.Send(BaseWriter writer) 
    at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer) 
    at System.Net.Mail.Message.Send(BaseWriter writer, Boolean sendEnvelope) 
    at System.Net.Mail.MailMessage.Send(BaseWriter writer, Boolean sendEnvelope) 
    at System.Net.Mail.SmtpClient.Send(MailMessage message) 

내가 스트림 대부분의 코드를 복사 : 나는 다음과 같은 오류가 받고 있어요

// snip 

List<System.Net.Mail.Attachment> attachments = null; 
// Attachments is a child list of Messagebody object holding Attachment ids 
MessageBody.Attachments = MessageBodyAttachmentList.GetMessageBodyAttachmentList(this.MessageBody.ID); 

if (MessageBody.Attachments != null && MessageBody.Attachments.Count > 0) 
{ 
    attachments = new List<Attachment>(); 

    foreach (Library.Entity.Messaging.MessageBodyAttachment att in MessageBody.Attachments) 
    { 
     using (MemoryStream memoryStream = new MemoryStream()) 
     { 
      // create a new attachment 
      Library.Attachments.Attachment attachment = Library.Attachments.Attachment.GetAttachment(att.AttachmentID); 

      byte[] contentAsBytes = attachment.FileData;// FileData holds byte[] that is the contents of the file 
      memoryStream.Write(contentAsBytes, 0, contentAsBytes.Length); 
      memoryStream.Seek(0, SeekOrigin.Begin); 

      // content type for file info 
      ContentType contentType = new ContentType(); 
      contentType.MediaType = MediaTypeNames.Application.Octet; 
      contentType.Name = attachment.FileName; 

      // create the .Net specific attachment 
      Attachment netAttachment = new Attachment(memoryStream, contentType); 
      attachments.Add(netAttachment); 

      memoryStream.Position = 0; 
     } 
    } 
} 

response = message.SendMessage(_recipient, _sender, _cc, _bcc, MessageBody.Subject, MessageBody.Body, true, attachments); 
// snip 

public string SendMessage(string to, string from, string cc, string bcc, string subject, string body, bool IsHtml, List<Attachment> attachments) 
{ 
    string response = String.Empty; 
    System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to, subject, body); 

    // Add the attachments 
    if (attachments != null) 
    { 
     foreach (Attachment a in attachments) 
      message.Attachments.Add(a); 
    } 

    message.IsBodyHtml = IsHtml; 

    if (IsHtml) 
    { 
     // snip 
    } 

    try 
    { 
     _client.Timeout = 500000; 
     _client.Send(message); 
    } 
    catch (SmtpException smtpex) 
    { 
     response = smtpex.Message; 
    } 
    catch (System.Exception ex) 
    { 
     response = ex.Message; 
    } 
    return response; 
} 

내가 웹에서 찾은 예에서.

+0

1. 탭 (공백 사용)을 사용하지 말고 웹용 서식을 쉽게 수정할 수 있습니다. 2. 스택 오버플로에 코드를 게시하려면 각 줄을 4 칸 들여 쓰기하십시오 (나중에 코드를 선택하고 Ctrl + K 또는 툴바 버튼 사용) –

답변

10

using 블록을 구현하지 않은 이유를 발견했습니다. 블록을 종료 한 후에도 개체를 계속 사용할 때입니다. using 블록에서 MemoryStream을 가져옵니다.

+1

네가 맞아, 사용중인 블록이 문제를 일으켰다. 나는 이것을 다음과 같이 재분할합니다 : memorystream ms = null; 경우 (내가 첨부 파일이있는) MS = 새로운 MemoryStream을()를 마 첨부 파일 생성 메시지 보내기 (밀리! = NULL)이 정리 도와 감사를 수행합니다. –

+2

어떻게 메모리 스트림을 사용하여 여러 첨부 파일을 처리 했습니까? 나는 1을 만들었고 수동으로 처리했지만 더 좋은 방법이 있는지 알고 싶었고 어떤 메모리 누수도 발생하지 않도록하고 싶었다. - thx –

+0

나는 같은 질문을 가지고있다. – Kate

관련 문제