首页 > 解决方案 > 如何从解决方案中删除任何动态创建的文件?

问题描述

我在解决方案的目录中创建一个文件,如下所示:

var targetPathToCreate = Path.Combine(HttpRuntime.AppDomainAppPath, "FolderName");

DirectoryInfo dirInfo = new DirectoryInfo(targetPathToCreate);

if (!dirInfo.Exists)
{
    dirInfo.Create();
}

var filePath = Path.Combine(targetPathToCreate, "FileName");
System.IO.File.WriteAllBytes(filePath, bytesArray);

此外,我正在通过电子邮件发送此文档,然后尝试删除此文档。

为此,我尝试了以下代码:

System.IO.File.Delete("FilePath");

但是这一行抛出了一个异常:

该进程无法访问该文件,因为它正被另一个进程使用

有没有办法通过克服异常来删除文件?

标签: c#fileio

解决方案


您可以使用垃圾收集器的WaitForPendingFinalizers函数。它将暂停当前线程,直到正在处理终结器队列的线程清空该队列。

   if (System.IO.File.Exists(filePath))
    {
      System.GC.Collect();
      System.GC.WaitForPendingFinalizers();
      System.IO.File.Delete(filePath);
    }

如果这不起作用,您必须处理您的邮件对象。

mail.Attachments.Add(...);
smtpServer.Send(mail);
mail.Dispose();
System.IO.File.Delete(filePath);

推荐阅读