删除文件报错(进程无法访问文件..)
Deleting files gives an error (The process cannot access the file..)
我目前正在调试我的代码,因为它给我一个错误:
The process cannot access the file because it is being used by another process.
而且我认为错误发生在这行代码中
foreach (var filename in filenames)
{
var file = Path.Combine(filePath, filename);
mail.Attachments.Add(new Attachment(file));
}
// Send Mail
smtpServer.Send(mail);
DeleteFiles();
我想用此方法发送邮件时删除文件夹中的文件
private void DeleteFiles()
{
string filePath = Server.MapPath("~/Content/attachments");
Array.ForEach(Directory.GetFiles(filePath), System.IO.File.Delete);
}
我读到 closing/disposing? FileStream 等,但我如何在我的代码中使用它?提前致谢。
using(FileStream stream = new FileStream("thepath"))
{
//do stuff with the file
stream .Close();
}
现在将关闭并处理该流。
mail.dispose();
您应该在删除文件之前处理邮件。 应该 解除对文件的锁定。
foreach (var filename in filenames)
{
var file = Path.Combine(filePath, filename);
mail.Attachments.Add(new Attachment(file));
}
// Send Mail
smtpServer.Send(mail);
mail.Dispose();
DeleteFiles();
https://msdn.microsoft.com/en-us/library/0w54a951(v=vs.110).aspx
我目前正在调试我的代码,因为它给我一个错误:
The process cannot access the file because it is being used by another process.
而且我认为错误发生在这行代码中
foreach (var filename in filenames)
{
var file = Path.Combine(filePath, filename);
mail.Attachments.Add(new Attachment(file));
}
// Send Mail
smtpServer.Send(mail);
DeleteFiles();
我想用此方法发送邮件时删除文件夹中的文件
private void DeleteFiles()
{
string filePath = Server.MapPath("~/Content/attachments");
Array.ForEach(Directory.GetFiles(filePath), System.IO.File.Delete);
}
我读到 closing/disposing? FileStream 等,但我如何在我的代码中使用它?提前致谢。
using(FileStream stream = new FileStream("thepath"))
{
//do stuff with the file
stream .Close();
}
现在将关闭并处理该流。
mail.dispose();
您应该在删除文件之前处理邮件。 应该 解除对文件的锁定。
foreach (var filename in filenames)
{
var file = Path.Combine(filePath, filename);
mail.Attachments.Add(new Attachment(file));
}
// Send Mail
smtpServer.Send(mail);
mail.Dispose();
DeleteFiles();
https://msdn.microsoft.com/en-us/library/0w54a951(v=vs.110).aspx