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

问题描述 投票:0回答:1

我正在如下所示将文件创建到解决方案的目录中:

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# file io
1个回答
0
投票

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

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

0
投票

我看了一眼,发现错误可能是由于您的代码System.IO.File.WriteAllBytes(filePath, bytesArray);可能没有在执行中完成。

这里是resource,您可以查看。您还可以通过编写一种新方法来获得新生成的文件的名称,该方法会将其邮寄然后删除,其中可能包括以下内容:

System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\"MyFiles\" + yourfilename + "'");
        try
        {
            fi.Delete();
        }
© www.soinside.com 2019 - 2024. All rights reserved.