문제

C#에서 작성하는 약간의 코드에 문제가 있습니다.

MailMessage 및 SMTP 구성 요소를 사용하여 문서를 보내고 있습니다. C : temp와 같은 임시 디렉토리로 보내려는 파일을 복사하고 문서를 살펴보고 이메일에 첨부합니다.

이메일은 정상적으로 보내지 만 Temp 디렉토리에서 파일을 삭제하려고하면 다음 오류가 발생합니다.

프로세스는 다른 프로세스에서 사용 중이므로 파일에 액세스 할 수 없습니다.

왜 이런 일이 일어나고 있는지 이해할 수 없습니다. 아래는 문서를 처리하는 코드입니다

public void sendDocument(String email, string barcode, int requestid)
    {

        string tempDir = @"c:\temp";

        //first we get the document information from the database.
        Database db = new Database(dbServer, dbName, dbUser, dbPwd);

        List<Document> documents = db.getDocumentByID(barcode);
        int count = 0;
        foreach (Document doc in documents)
        {
            string tempPath = tempDir + "\\" + doc.getBarcode() + ".pdf";
            string sourcePath = doc.getMachineName() + "\\" + doc.getFilePath() + "\\" + doc.getFileName();

            //we now copy the file from the source location to the new target location
            try
            {
                //this copies the file to the folder
                File.Copy(sourcePath, tempPath, false);

            }
            catch (IOException ioe)
            {
                count++; 

                //the file has failed to copy so we add a number to the file to make it unique and try
                //to copy it again.
                tempPath = tempDir + "\\" + doc.getBarcode() + "-" + count + ".pdf";
                File.Copy(sourcePath, tempPath, false);

            }

            //we now need to update the filename in the to match the new location
            doc.setFileName(doc.getBarcode() + ".pdf");                

        }

        //we now email the document to the user.
        this.sendEmail(documents, email, null);

        updateSentDocuments(documents, email);

        //now we update the request table/
        db.updateRequestTable(requestid);


        //now we clean up the documents from the temp folder.
        foreach (Document doc in documents)
        {
            string path = @"c:\temp\" + doc.getFileName();
            File.Delete(path);
        }

    }

나는 삭제가 실패하는 SMTP 객체라고 생각하기 때문에 this.sendemail () 메소드가 SendDocument 메소드로 돌아 오기 전에 이메일을 보냈다고 생각합니다.

이것은 SendEmail 메소드입니다.

public void sendEmail(List<Document> documents, String email, string division)
    {
        String SMTPServer = null;
        String SMTPUser = null;
        String SMTPPwd = null;
        String sender = "";
        String emailMessage = "";

        //first we get all the app setting used to send the email to the users
        Database db = new Database(dbServer, dbName, dbUser, dbPwd);

        SMTPServer = db.getAppSetting("smtp_server");
        SMTPUser = db.getAppSetting("smtp_user");
        SMTPPwd = db.getAppSetting("smtp_password");
        sender = db.getAppSetting("sender");
        emailMessage = db.getAppSetting("bulkmail_message");

        DateTime date = DateTime.Now;

        MailMessage emailMsg = new MailMessage();

        emailMsg.To.Add(email);

        if (division == null)
        {
            emailMsg.Subject = "Document(s) Request - " + date.ToString("dd-MM-yyyy");
        }
        else
        {
            emailMsg.Subject = division + " Document Request - " + date.ToString("dd-MM-yyyy");
        }

        emailMsg.From = new MailAddress(sender);
        emailMsg.Body = emailMessage;

        bool hasAttachements = false;

        foreach (Document doc in documents)
        {

            String filepath = @"c:\temp\" + doc.getFileName();

            Attachment data = new Attachment(filepath);
            emailMsg.Attachments.Add(data);

            hasAttachements = true;


        }

        SmtpClient smtp = new SmtpClient(SMTPServer);

        //we try and send the email and throw an exception if it all goes tits.
        try
        {
            if (hasAttachements)
            {
                smtp.Send(emailMsg);
            }
        }
        catch (Exception ex)
        {
            throw new Exception("EmailFailure");
        }


    }

삭제하려는 파일을 호그하는 프로세스 로이 문제를 해결하는 방법.

응용 프로그램이 완료되면 파일을 삭제할 수 있습니다.

도움이 되었습니까?

해결책

이메일 메시지가 폐기되지 않습니다. 보낸 후 처리 해보세요.

 try
 {
      if (hasAttachements)
      {
          smtp.Send(emailMsg);         
      }
 }  
 catch ...
 finally
 {
      emailMsg.Dispose();
 }

다른 팁

첫 번째 단계는 문제의 파일에 어떤 프로세스를 보유하고 있는지 파악하는 것입니다. sysinternals 툴킷을 잡고 handle.exe 명령을 사용하여 파일에 어떤 프로세스를 보유하고 있는지 확인합니다.

파일이 어떤 프로세스가 열려 있는지 모르면이 문제를 해결할 방법이 없습니다.

sysinternals 링크 : http://technet.microsoft.com/en-us/sysinternals/default.aspx

내가 방금 발견 한 트릭은 다음과 같습니다. 메시지에 첨부 파일을 추가하기 전에 래퍼를 사용하여 첨부 파일을 만듭니다. 이를 통해 올바르게 폐기하여 파일을 성공적으로 삭제할 수 있습니다. Send 가이 루프에 있어야하는지 확실하지 않습니다. (테스트를했을 때, 이메일은 처음에는 통과되지 않았고 30 분 후에 침수되어 네트워크가 조금 더 차분한 시간 동안 테스트를 떠나기로 결정했습니다).

using (Attachment attachment = new Attachment(filename))
{
    message.Attachments.Add(attachment);
    client.SendAsync(message, string.Empty);
}
File.Delete(filename);

어쨌든 나를 위해 잘 작동합니다 :)

행운을 빕니다,

JB

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top