How to delete files saved on the server after sending and email with SMTP client in MVC application

StackOverflow https://stackoverflow.com/questions/19840782

Pergunta

I have a project on M.V.C 4 C# internet application and i have followed some guides to save Google visualization column chart to an image to my drive with ajax function.Also i am making a P.D.F format report with razor P.D.F nugget package.The path is: "C\temp\" and both files are there.I need to attach both files to an email and send them and then to delete the created files.

I call the send email function with ajax :

$('#btnSend').on('click', function () {
            if (from) {
                fromDate = from.toJSON();
            }

            if (to) {
                toDate = to.toJSON();
            }
            // from and to are dates taken from two datepickers

            // saves the pdf to the server
            if (from && to) {
                $.ajax({
                    url: "/Home/SavePdf/",
                    data: { fromDate: fromDate, toDate: toDate },
                    type: 'GET',
                    async: false,
                    datatype: 'json',
                    success: function (data) {
                        alert('got here with data');
                    },
                    error: function () { alert('something bad happened'); }
                });
            }


            // saves the column chart to the server from canvas item with id reports

            var imgData = getImgData(document.getElementById("reports"));
            var imageData = imgData.replace('data:image/png;base64,', '');

            $.ajax({
                url: "/Home/SaveImage/",
                type: 'POST',
                data: '{ "imageData" : "' + imageData + '" }',
                datatype: 'json',
                async: false,
                contentType: 'application/json; charset=utf-8',
                success: function () {
                    alert('Image saved successfully !');
                },
                error: function () {
                    alert('something bad happened');
                }
            });

            $.ajax({
                type: "POST",
                url: "/Home/SendMail/",
                async: false,
                success: function() {
                    alert('Message sent successfully');
                }
            });
        });

and here is my function in the code behind

public void SendMail()
        {
            var path = @"C:\temp\";
            string pngFilePath = path + DateTime.Now.ToShortDateString() + ".png";
            string pdfFilePath = path + DateTime.Now.ToShortDateString() + ".pdf";

            MailMessage message = new MailMessage("message sender", "message reciever")
            {
                Subject = "Test",
                Body = @"Test"
            };
            Attachment data = new Attachment(pdfFilePath , 

 MediaTypeNames.Application.Pdf);
        message.Attachments.Add(data);

        Attachment data2 = new Attachment(pngFilePath , GetMimeType(pngFilePath); 
 // GetMimeType function gets the mimeType of the unknown attachment
        message.Attachments.Add(data2);

        SmtpClient client = new SmtpClient();
        client.Host = "smtp.googlemail.com";
        client.Port = 587;
        client.UseDefaultCredentials = true;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.EnableSsl = true;
        client.Credentials = new NetworkCredential("mail sender", "sender password");
        client.Send(message);

        // delete the png after message is sent
        if ((System.IO.File.GetAttributes(pngFilePath ) & FileAttributes.Hidden) == FileAttributes.ReadOnly) 
        {

            System.IO.File.SetAttributes(pngFilePath , FileAttributes.Normal);            

            if (System.IO.File.Exists(pngFilePath ))  
            {     
                System.IO.File.Delete(pngFilePath ); 
            }  
        }

        // delete the pdf after message is sent
        if ((System.IO.File.GetAttributes(pdfFilePath ) & FileAttributes.Hidden) == FileAttributes.ReadOnly)
        {

            System.IO.File.SetAttributes(pdfFilePath , FileAttributes.Normal);

            if (System.IO.File.Exists(pdfFilePath ))
            {
                System.IO.File.Delete(pdfFilePath );
            }
        }
    }

I want to delete those files, but IIS continues to use them and delete operation is never reached. Is there any way to disattach those files from iis and delete them ?

Foi útil?

Solução

It's SmtpClient that locks the files. Create a stream for each file and use that as an attachment. Something like this:

using(Stream fs1 = File.OpenRead(pdfFilePath))
using(Stream fs2 = File.OpenRead(pngFilePath))
{
   Attachment data = new Attachment(fs1 , GetMimeType(pdfFilePath));
   Attachment data2 = new Attachment(fs2 , GetMimeType(pngFilePath));
   message.Attachments.Add(data);
   message.Attachments.Add(data2);
   ...
   client.Send(message);
}

EDIT: My initial suggestion, to use client.Dispose() after sending the mail, doesn't seem to work

Outras dicas

I add the same problem and I saw previous answer.

It is possible to use client.Dispose() but you alse have to do message.Attachments.Dispose().

After that you can delete your file.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top