问题描述
我的控制台应用程序正在运行时正在创建一些运行时文件,因此我想做的是在应用程序启动时删除所有这些文件.我已经尝试过:
My console application program is creating some runtime files while it is working so what I want to do is delete all of these files on the application startup. I have tried this:
public static void Empty(string targetDir)
{
var directory = new DirectoryInfo(targetDir);
if (!directory.Exists) return;
foreach (var file in directory.GetFiles()) file.Delete();
foreach (var subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}
...只是在给定路径(位于程序执行路径的子目录中)中查找所有文件/文件夹,然后将其删除.但是,出现以下异常:
...just to look for all the files/folders in the given path (which is in a subdirectory in the program execution path) then delete them. However, I get the following exception:
我试图以管理员身份运行该程序,但是没有运气.但是,我需要一种无需使用管理员权限即可使用的解决方案.
I tried to run the program as administrator with no luck; However, I want a solution that works without using administrator privileges.
注意:
- 该文件未在其他应用程序中运行.
- 该文件不在受保护的文件夹中.
- 可以毫无问题地手动删除文件,这就是为什么我在这里.
- The file is not running in another application.
- The file is not in a protected folder.
- The file can be deleted manually with no problems and that's why iam here.
推荐答案
尝试使用Microsoft.VisualBasic.FileIO.FileSystem
方法,因为它具有方便的DeleteDirectory
方法,我前一段时间遇到了访问麻烦,这是解决我的问题的方法. /p>
Try using the Microsoft.VisualBasic.FileIO.FileSystem
methods as it has a handy DeleteDirectory
method, I had access troubles awhile ago and this was the fix for my problem.
var directory = new DirectoryInfo(targetDir);
if (directory.Exists)
{
Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(targetDir, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents);
}
这篇关于File.Delete拒绝访问该路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!