Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

File in use after email as attachment

Posted on 2006-06-26
11
311 Views
Last Modified: 2008-01-09
I made a form where the user can fill it out, browser for a file, and then click submit.  I have it setup so the form data is emailed to me along with the attachment.  It works except I can not delete the attachment from the server because it is still in use.  Why is the file still in use after emailing it out?  If I remove this line   (upload the attachment but dont send it in the email)  then the file is not in use and I can delete it after.)  Why when I add the following line is the file in use after and can not be deleted??

message.Attachments.Add(new Attachment(strdir + strfilename));
0
Comment
Question by:Kurt4949
  • 5
  • 4
  • 2
11 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 16987756
.NET version?  2002, 2003, or 2005?

Bob
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 16987796
Should it be MailAttachment, instead of Attachment?

Bob
0
 
LVL 7

Author Comment

by:Kurt4949
ID: 16987813
For example if I tell asp.net to delete the file after then I get this error


 Exception Details: System.IO.IOException: The process cannot access the file 'D:\wwwTesting\promessInc\upload\forms.css' because it is being used by another process.

Source Error:

Line 114:
Line 115:            //Uploaded file deleted after sending e-mail
Line 116:                File.Delete(strdir + strfilename);
Line 117:      
Line 118:            
0
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
LVL 7

Author Comment

by:Kurt4949
ID: 16987824
asp.net 2.0 with C#
0
 
LVL 7

Author Comment

by:Kurt4949
ID: 16987877
I believe that line is correct.  I"m using System.Net.Mail

example here http://www.systemnetmail.com/faq/2.3.aspx 
0
 
LVL 4

Expert Comment

by:davehunt00
ID: 16987998
Here's a similar set of code I use. r2("Attachment") is a field with the file name.  You might want to add the Try Catch stuff in case you ever hit an exception.

        If (r2("Attachment").ToString <> "") Then
            Dim MsgAttachmentPath As String = Server.MapPath(r2("Attachment").ToString)
            Dim attachment As System.Web.Mail.MailAttachment                  
            Try
                attachment = New System.Web.Mail.MailAttachment(MsgAttachmentPath)
                emailMessage.Attachments.Add(attachment)
            Catch ex As Exception
                Dim sb As New System.Text.StringBuilder
                sb.Append("my note about where this occurs")
                sb.Append("Message: " & ex.Message.ToString)
                sb.Append("InnerException: " & ex.InnerException.ToString)
                sb.Append("Target site: " & ex.TargetSite.Name.ToString)
                sb.Append("Stack Trace: " & ex.StackTrace.ToString)
                exString = sb.ToString
                SendErrorEmail(exString)
            End Try
        End If

Hope that helps.  
Dave
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 16988055
Yeah, what happens if you use System.Web.Mail, instead of System.Net.Mail?

Bob
0
 
LVL 7

Author Comment

by:Kurt4949
ID: 16988109
Here is my code.  It works perfect execpt that I can not delete the attachement after.  I even get the email with the attachment.    


void submitForm(Object s, EventArgs e)
    {
        if (Page.IsValid == true)
        {

            string fromEmail;
            string toEmail;
            string userHostAddress = "";


            string strdir = "D:\\wwwTesting\\files\\upload\\";
            string strfilename = Path.GetFileName(txtFile.PostedFile.FileName);
            txtFile.PostedFile.SaveAs(strdir + strfilename);
           

            fromEmail = "webmaster@me.com";
            toEmail = "kurt@me.com";
            //get IP Address
            userHostAddress = Request.UserHostAddress;


            // System.Net.Mail.SmtpClient is the new class in 2.0
            SmtpClient smtpClient = new SmtpClient();
            MailMessage message = new MailMessage();
           
           
            try
            {
              smtpClient.Host = "localhost";
            smtpClient.Port = 25;
            message.From = new MailAddress(fromEmail);

            message.To.Add(toEmail);
            message.Subject = " Form Submission";
 
            //Begin - Message body content
            message.IsBodyHtml = true;

            //html message body
            message.Body = "<html>" +
                           "<head>" +
                           "<title>Form Submission</title>" +
                           "</head>" +

                           "<body>" +
                           "<font face=\"Arial, Helvetica, sans-serif\" size=\"2\">" +
                           "<b>Form Submission</b><br /><br />" +
                           "<b>Salutation:</b>    " + salutation.Text +
                            "<br /><b>First name:</b>   " + fName.Text +
                            "<br /><b>Last name:</b>     " + lName.Text +
                            "<br /><br /><b>Comments:</b><br /> " + comments.Text +
                            "</font></body></html>";

            //End - Message body content
       
            //Attach File
            message.Attachments.Add(new Attachment(strdir + strfilename));


            // Send SMTP mail
            smtpClient.Send(message);

            // on success hide / show panels
            lblStatus.Text = "Email successfully sent.";
            panelContactForm.Visible = false;
            panelThankYou.Visible = true;

            }
            catch (Exception ex)
            {
                lblStatus.Text = "Send Email Failed.<br>" + ex.Message;

            }


            //Uploaded file deleted after sending e-mail
                File.Delete(strdir + strfilename);
     
           
        }//end if Page.IsValid

    }

</script>
0
 
LVL 4

Expert Comment

by:davehunt00
ID: 16988183
More as a guess than anything, try clearing the attachments.

So, before File.Delete, try Message.Attachments.Clear


0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 16988333
If you create a 'using' block, the message should be disposed upon completion.  If you force garbage collection (used judiciously), then it should release the resources immediately.

void submitForm(Object s, EventArgs e)
    {
        if (Page.IsValid == true)
        {

            string fromEmail;
            string toEmail;
            string userHostAddress = "";


            string strdir = "D:\\wwwTesting\\files\\upload\\";
            string strfilename = Path.GetFileName(txtFile.PostedFile.FileName);
            txtFile.PostedFile.SaveAs(strdir + strfilename);
           

            fromEmail = "webmaster@me.com";
            toEmail = "kurt@me.com";
            //get IP Address
            userHostAddress = Request.UserHostAddress;

            // System.Net.Mail.SmtpClient is the new class in 2.0
            SmtpClient smtpClient = new SmtpClient();
            using (MailMessage message = new MailMessage())
            {
                       
               try
              {
                 smtpClient.Host = "localhost";
                 smtpClient.Port = 25;
                 message.From = new MailAddress(fromEmail);

                 message.To.Add(toEmail);
                 message.Subject = " Form Submission";
 
                //Begin - Message body content
                message.IsBodyHtml = true;

            //html message body
            message.Body = "<html>" +
                           "<head>" +
                           "<title>Form Submission</title>" +
                           "</head>" +

                           "<body>" +
                           "<font face=\"Arial, Helvetica, sans-serif\" size=\"2\">" +
                           "<b>Form Submission</b><br /><br />" +
                           "<b>Salutation:</b>    " + salutation.Text +
                            "<br /><b>First name:</b>   " + fName.Text +
                            "<br /><b>Last name:</b>     " + lName.Text +
                            "<br /><br /><b>Comments:</b><br /> " + comments.Text +
                            "</font></body></html>";

            //End - Message body content
       
            //Attach File
            message.Attachments.Add(new Attachment(strdir + strfilename));


            // Send SMTP mail
            smtpClient.Send(message);

            // on success hide / show panels
            lblStatus.Text = "Email successfully sent.";
            panelContactForm.Visible = false;
            panelThankYou.Visible = true;

            }
            catch (Exception ex)
            {
                lblStatus.Text = "Send Email Failed.<br>" + ex.Message;

            }


            }// end using      

            // Force garbage collection to close the message immediately.
            GC.Collect();
           
            //Uploaded file deleted after sending e-mail
                File.Delete(strdir + strfilename);

        }//end if Page.IsValid

    }

Bob
0
 
LVL 7

Author Comment

by:Kurt4949
ID: 16993047
Hi Bob,

The using blocked did the trick. Thanks!

using (MailMessage message = new MailMessage())
            {
}


Kurt
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question