gpt4 book ai didi

c# - 使用 TempFileCollection 在 ASP.NET MVC C# 中删除临时文件

转载 作者:行者123 更新时间:2023-11-30 23:31:19 25 4
gpt4 key购买 nike

我对 ASP.NET 5 MVC C# 中的临时文件有疑问。我想生成一个ics文件,然后将其存储为一个临时文件,用邮件发送,然后删除该文件。我在我的本地主机上尝试这个。我正在启动应用程序,然后执行 API GET 调用(通过浏览器 ....net/api/quotes)并在 GET 方法中启动 sendMailWithIcal 方法。调用 API 后,我在 Visual Studio 中停止应用程序。

通过搜索 stackoverflow,我找到了 TempFileCollection。问题是我发送邮件后无法删除文件。我尝试了两种不同的方法,使用:“System.IO.File.Delete(path)”或使用“tempFiles.Delete()”:

public void SendMailWithICal(string receiver, string subject, string textBody)
{

this._msg = new MailMessage(UserName, receiver);
this._msg.Subject = subject;
this._msg.Body = textBody;

CalenderItems iCalender = new CalenderItems();
iCalender.GenerateEvent("Neuer Kalendereintrag");

var termin = iCalender.iCal;

using (var tempFiles = new TempFileCollection())
{
tempFiles.AddFile("TempIcsFiles/file3.ics", false);
System.IO.File.WriteAllText("TempIcsFiles/file3.ics", termin.ToString());

Attachment atm = new Attachment("TempIcsFiles/file3.ics");
this._msg.Attachments.Add(atm);

System.IO.File.Delete(("TempIcsFiles/file3.ics")); //Either i try this
//tempFiles.Delete(); //or this
}
this._smtpClient.Send(_msg);
}

如果我用 System.IO.File.Delete 尝试它,我会收到一个异常,它无法访问该文件,因为它已被另一个进程使用。如果我使用 tempfiles.Delete(),没有异常(exception),它会发送邮件,但文件不会从 wwwroot 文件夹内的文件夹 TempIcsFiles 中删除

感谢您的帮助。

编辑:我用这段代码尝试了 Mikeal Nitell 的解决方案:

var termin = iCalender.iCal;

using (var tempFiles = new TempFileCollection())
{
tempFiles.AddFile("TempIcsFiles/file6.ics", false);

//tempFiles.Delete();
System.IO.File.WriteAllText("TempIcsFiles/file6.ics", termin.ToString());

Attachment atm = new Attachment("TempIcsFiles/file6.ics");

this._msg.Attachments.Add(atm);
this._smtpClient.Send(_msg);
this._msg.Dispose();
atm.Dispose();
}
System.IO.File.Delete(("TempIcsFiles/file6.ics"));

现在我收到无法访问该文件的 IOException,因为另一个进程正在使用它,已经在“System.IO.File.WriteAllText(...)”行中

如果我取消注释这一行,我会在初始化附件的后面的一行收到 FileNotFoundException。

最佳答案

您需要处理您的 MailMessage。它会锁定您附加的文件,并且在处理消息对象之前不会释放这些锁定。这就是为什么当您尝试删除文件时会出现异常,这也是 TempFileCollection 无法删除它的原因。

因此,您需要将 MailMessage 放在 using 语句中,或者在释放 TempfileCollection 之前对其显式调用 Dispose。

关于c# - 使用 TempFileCollection 在 ASP.NET MVC C# 中删除临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34635372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com