i've got a problem with closing a temporary file. In my method I'm, generating an ics file, write text in it and then send it using MimeMail. The problem is that I don't know how to close the path so that I can access it to delete it after the mail was send. And MimeMail does not provide a solution like message.Dispose() or message.Close().
Here is my code:
public void SendEmailWithICal(string toEmailAddress, string subject, string textBody)
{
var message = new MimeMessage();
message.From.Add(
new MailboxAddress("Chronicus Dev", this.UserName));
message.To.Add(new MailboxAddress(toEmailAddress.Trim(), toEmailAddress.ToString()));
message.Subject = subject;
CalenderItems iCalender = new CalenderItems();
iCalender.GenerateEvent("Neuer Kalendereintrag");
var termin = iCalender.iCal;
string path = "TempIcsFiles/file.ics";
if (File.Exists(path))
{
File.Delete(path);
}
{
// Create File and Write into it
FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
StreamWriter str = new StreamWriter(fs);
str.BaseStream.Seek(0, SeekOrigin.End);
str.Write(termin.ToString());
//Close Filestream and Streamwriter
str.Flush();
str.Dispose();
fs.Dispose();
//Add as Attachment
var attachment = new MimePart("image", "gif")
{
ContentObject = new ContentObject(File.OpenRead(path), ContentEncoding.Default),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = Path.GetFileName(path)
};
var body = new TextPart("plain")
{
Text = "Meine ICal Mail"
};
//Configure Email
var multipart = new Multipart("mixed");
multipart.Add(body);
multipart.Add(attachment);
message.Body = multipart;
//Send Email
using (var client = new SmtpClient())
{
client.Connect(HostName, Port, false);
client.Authenticate(UserName, Password);
client.Send(message);
client.Disconnect(true);
}
//TODO Close File
//Trying to Delete, but Exception
File.Delete(path);
}
}
Thanks for any help!