Question

I am creating a new *.csv file and after creating it I want to send this file as an attachment in an email but file is locked for 10 - 15 seconds. Is there any way to wait file to be released and then send this file wihout getting any exception: The process cannot access the file because it is being used by another process.

File.WriteAllText("test.csv", sb.ToString(),Encoding.UTF8);
SendMail();

 private static void SendMail()
    {
     MailMessage mail = new MailMessage("from", "to");
        SmtpClient client = new SmtpClient();
        client.Port = 25;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Host = "host";
        mail.Subject = "this is subject";
        mail.Body = "this is body";
        mail.Attachments.Add(new Attachment("test.csv"));
        mail.IsBodyHtml = true;
        client.Send(mail);
}

If I wait with Thread.Sleep() I am able to send email successfully but I do not want to use it. I do not know the exact time when file operation is completed. It is a console app. Any suggestions?

No correct solution

OTHER TIPS

Why do you need to write file to disk and to read it again when attachent is created? I guess you can use methods when attachment is created from ready string.

// Attach the message string to this e-mail message.
Attachment data = new Attachment(textMessage, MediaTypeNames.Text.Plain);
data.Name = "test.csv";

Found here: http://msdn.microsoft.com/ru-ru/library/9089e309(v=vs.110).aspx Or try this method: http://msdn.microsoft.com/ru-ru/library/ms144617(v=vs.110).aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top