c# - 如何从解决方案中删除任何动态创建的文件?
问题描述
我在解决方案的目录中创建一个文件,如下所示:
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");
但是这一行抛出了一个异常:
该进程无法访问该文件,因为它正被另一个进程使用
有没有办法通过克服异常来删除文件?
解决方案
您可以使用垃圾收集器的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);
推荐阅读
- mysql - laravel [1049] 未知数据库
- android - Android - Changing Gradle.properties according to flavor
- swift - How to add a custom view from a xib to a UIScrollView?
- sparql - How to retrieve and delete a JSON-LD tree from a triple store using SPARQL?
- reactjs - React defaultProps 不会填充缺少的对象道具
- text-alignment - 如何更改 DOORS 中的文本时间?
- docker - 将 /var/run/docker.sock 挂载到容器中时,使用哪个文件系统进行卷挂载?
- sql - Is this INSERT INTO SSMS query safe from SQL injection?
- javascript - Error trying to save to local storage with Vue.JS
- python - 如何使用 cx_Freeze 将一些 .py 文件“隐藏”到 .exe 中?