0

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?

cihadakt
  • 3,054
  • 11
  • 37
  • 59
  • File.WriteAllText should be closing the file immediately when it is complete. Something is wrong. You can try using StreamWriter and opening and closing it explicitly. Otherwise, perhaps something outside your app is tampering with it. – Matt J. Dec 05 '13 at 07:21
  • It is strange but File.WriteAllText doesnt close the file immediately. StreamWriter solves my problem. Thank you. By the way, I just wonder is there any way to wait file releasing or any event like filerelease_completed? – cihadakt Dec 05 '13 at 07:56
  • Glad to hear StreamWriter did the trick. I'm not sure how one would watch for a release other than to just check for it. – Matt J. Dec 05 '13 at 22:50

1 Answers1

0

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

Tony
  • 7,345
  • 3
  • 26
  • 34