좋은 날,
첨부 파일을 보내는 이메일에 파일 스트림 파일을 첨부하려고합니다. 시나리오는을 사용하여 파일을 FileStream
만든 다음 내 이메일에 첨부해야한다는 것입니다.
지금까지 내 샘플 코드는 다음과 같습니다.
파일 생성 :
public FileStream CreateFileStream(){
using (var ms = new MemoryStream())
{
var writer = new StreamWriter(ms);
writer.WriteLine("file content blah blah blahh");
writer.Flush();
//You have to rewind the MemoryStream before copying
ms.Seek(0, SeekOrigin.Begin);
using (var fs = new FileStream("Filename.txt", FileMode.Create))
{
ms.CopyTo(fs);
return fs;
}
}
}
다음은 이메일 전송을위한 샘플 코드입니다.
// attachment
var fileStreamFile = dto.FileStreamFile;
var contentType = new ContentType(MediaTypeNames.Text.Plain);
var attach = new Attachment(dto.FileStreamFile, contentType);
attach.ContentDisposition.FileName = "File.txt";
mail.Attachments.Add(attach);
...
// code for sending here
...
dto.FileStreamFile.Dispose(); // for disposing File Stream
fileStreamFile
null이 아니지만 다음과 같은 오류가 발생합니다.
Handle = 'dto.FileStreamFile.Handle' threw an exception of type 'System.ObjectDisposedException'
첨부 코드를 주석 처리하면 어쨌든 이메일 전송이 정상적으로 작동합니다. 첨부 할 코드를 포함하면 이메일 전송이 실패합니다.FileStream
도와주세요. 미리 감사드립니다
귀하의 코드
using (var fs = new FileStream("Filename.txt", FileMode.Create))
{
ms.CopyTo(fs);
return fs; // you are returning here
} // hang on, this is a using statement which will dispose fs!
이것으로 번역됩니다
FileStream fileStream = new FileStream("Filename.txt", FileMode.Create);
try
{
return fileStream;
}
finally
{
if (fileStream != null)
{
((IDisposable)fileStream).Dispose();
}
}
return
에있는 경우 try finally
반환 값을 로컬 변수에 저장하여 finally
. 다음과 같이 보일 것입니다.
FileStream fileStream = new FileStream("Filename.txt", FileMode.Create);
try
{
temp = fileStream;
}
finally
{
if (fileStream != null)
{
((IDisposable)fileStream).Dispose();
}
}
return temp;
무슨 일이 일어나고 있는지 알아보기 위해 IL 을 살펴볼 수 있습니다.
IL_0000: ldstr "someFile"
IL_0005: ldc.i4.2
IL_0006: newobj instance void [mscorlib]System.IO.FileStream::.ctor(string, valuetype[mscorlib]System.IO.FileMode)
// stloc.0 Pops the current value from the top of the evaluation stack and stores it in the
// local variable list at a specified index. This is your fs reference
IL_000b: stloc.0
.try
{
// ldloc.0 Loads the local variable at a specific index onto the evaluation stack.
// This is your fs reference
IL_000c: ldloc.0
// stloc.1 Pops the current value from the top of the evaluation stack and stores it in
// the local variable list at a specified index. This is your fs reference
IL_000d: stloc.1
IL_000e: leave.s IL_001a
} // end .try
finally
{
IL_0010: ldloc.0
IL_0011: brfalse.s IL_0019
IL_0013: ldloc.0
// oh no we just Disposed fs!!!
IL_0014: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0019: endfinally
} // end handler
// ldloc.1 Loads the local variable at a specific index onto the evaluation stack.
// This is your fs reference
IL_001a: ldloc.1
//ret Returns from the current method, pushing a return value (if present) from
//the callee's evaluation stack onto the caller's evaluation stack.
IL_001b: ret
짧은에서는, 반환하지 않는 IDisposable
A로부터 참조를 using
가 얻을 것이다으로 문 배치 .
다른 컨텍스트에서 FileStream
(없이 using
) 생성 Dispose
하거나 코드를 리팩터링해야합니다.
최신 정보
하지만 스트림으로 이메일 전송을 다루는 using 문을 입력 한 후 내 이메일 전송이 작동하지 않습니다.
당신은 이것을 지나치게 복잡하게 만들 수 있습니다.
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream)) // using UTF-8 encoding by default
using (var mailClient = new SmtpClient("localhost", 25))
using (var message = new MailMessage("[email protected]", "[email protected]", "Just testing", "See attachment..."))
{
writer.WriteLine("file content blah blah blahh");
writer.Flush();
stream.Position = 0; // read from the start of what was written
message.Attachments.Add(new Attachment(stream, "filename.csv", "text/csv"));
mailClient.Send(message);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다