ASP.NET 5 / MVC 6 / C#:使用后关闭文件路径

时间:2016-01-07 16:50:58

标签: c# asp.net asp.net-mvc

关闭临时文件时遇到问题。在我的方法中,生成一个ics文件,在其中写入文本,然后使用MimeMail发送它。问题是我不知道如何关闭路径,以便我可以在邮件发送后访问它以删除它。并且MimeMail不提供message.Dispose()或message.Close()等解决方案。

这是我的代码:

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);
        }
    }

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

尝试重新定位File.OpenRead(路径), 并将整个消息对象包装在using()中,如下所示:

public void SendEmailWithICal(string toEmailAddress, string subject, string textBody)
{
    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 to it
    using (var fs = new FileStream(path, FileMode.OpenOrCreate))
    {
        using (var str = new StreamWriter(fs))
        {
            str.BaseStream.Seek(0, SeekOrigin.End);
            str.Write(termin.ToString());
            //Close Filestream and Streamwriter
            str.Flush();
        }
    }
    //Compose the message
    using (var read_stream = File.OpenRead(path))
    {
        using (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;
            //Add as Attachment
            var attachment = new MimePart("image", "gif")
            {
                ContentObject = new ContentObject(read_stream, 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);
            }
        }
    }
    //Delete temporary file
    File.Delete(path);
}

这应该保证一个关闭的文件,假设client.Send是一个完全同步的操作。

另请参阅此可能重复的https://stackoverflow.com/questions/1296380/smtp-send-is-locking-up-my-files-c-sharp

答案 1 :(得分:1)

使用此代码:

File.Create(FilePath).Close();
File.WriteAllText(FileText);