SMTP Send가 내 파일을 잠그고 있습니다 -C#
-
18-09-2019 - |
문제
메시지를 보내는 기능 (많은 메시지)과 첨부 파일이 있습니다.
기본적으로 디렉토리 구조를 살펴보고 예를 들어 파일 구조에서 이메일을 만듭니다.
c:\emails\message01
\attachments
c:\emails\message02
\attachments
메시지 작성은 표준 STAPTION .NET C#을 사용하여 이루어집니다.
모든 메시지가 작성된 후 ... 나중에 직접 실행되는 다른 기능이 있습니다. 메시지 폴더를 다른 위치에 복사합니다.
문제는 - 파일이 잠겨 있다는 것입니다 ...
참고 : 파일을 움직이지 않고 복사합니다 ....
C#을 사용하여 잠긴 파일을 복사하는 방법에 대한 제안이 있습니까?
업데이트
이 추가 첨부 방법이 있습니다
private void AddAttachments(MailMessage mail)
{
string attachmentDirectoryPath = "c:\messages\message1";
DirectoryInfo attachmentDirectory = new DirectoryInfo(attachmentDirectoryPath);
FileInfo[] attachments = attachmentDirectory.GetFiles();
foreach (FileInfo attachment in attachments)
{
mail.Attachments.Add(new Attachment(attachment.FullName));
}
}
해결책
이메일 메시지를 만들기 위해 파일을 어떻게 읽고 있습니까? 그것들은 a.와 함께 읽기 전용으로 열어야합니다 FileShare
로 설정 FileShare.ReadWrite
... 그러면 그들은 잠겨져서는 안됩니다. 사용중인 경우 FileStream
또한 논리를 래핑해야합니다 using
리소스가 제대로 폐기되도록 키워드.
업데이트:
메일 메시지 자체를 처분하면 리소스 내부의 리소스가 닫히고 파일을 잠금 해제한다고 생각합니다.
using (var mail = new MailMessage())
{
AddAttachments(mail);
}
// File copy code should work here
다른 팁
내 자신의 게시물에 응답하는 것을 싫어하지만,이 문제가있는 다음 가난한 사람은 여기에 수정이 있습니다.
메시지를 보낸 후
// Send the mail
client.Send(message);
//Clean up attachments
foreach (Attachment attachment in message.Attachments)
{
attachment.Dispose();
}
첨부 파일을 폐기하십시오 ... 잠금 장치를 지우고 메시지에는 여전히 첨부 파일이 전송됩니다. Dispose는 파일을 삭제하지 않으며 첨부 파일을 지우는 것만 지시합니다. :)
파일을 읽은 후 파일을 닫고 있습니까? 읽기를 위해 열 수 있지만 완료되면 닫지 않으면 프로그램이 종료되어 모든 파일을 자동으로 닫을 때까지 잠금을 유지해야합니다.
MailMessage email = new MailMessage();
email.From = txtFrom.Text;
email.To = txtToEmail.Text;
email.Subject = txtMSubject.Text;
email.Body = txtBody.Text;
SmtpClient mailClient = new SmtpClient();
mailClient.Host = "smtp.emailAddress";
mailClient.Port = 2525;
mailClient.Send(email );
email.Dispose();
// After Disposing the email object you can call file delete
if (filePath != "")
{
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
}
첨부 파일을 보낼 때 이것을 많이 본다. 나는 일반적으로 다음과 같은 것을 사용합니다.
파일을 다른 위치로 이동시키는 코드에서 다음 패턴을 사용할 수 있습니다.
파일을 통한 루프를위한 루프 내부
bool FileOk = false;
while (!FileOk)
{
try
{
// code to move the file
FileOk = true;
}
catch(Exception)
{
// do nothing or write some code to pause the thread for a few seconds.
}
}