File.Delete拒绝访问该路径 [英] File.Delete Access to the path is denied

查看:507
本文介绍了File.Delete拒绝访问该路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制台应用程序正在运行时正在创建一些运行时文件,因此我想做的是在应用程序启动时删除所有这些文件.我已经尝试过:

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:

拒绝访问文件"路径.

Access to the path 'file' is denied.

我试图以管理员身份运行该程序,但是没有运气.但是,我需要一种无需使用管理员权限即可使用的解决方案.

I tried to run the program as administrator with no luck; However, I want a solution that works without using administrator privileges.

注意:

  1. 该文件未在其他应用程序中运行.
  2. 该文件不在受保护的文件夹中.
  3. 可以毫无问题地手动删除文件,这就是为什么我 在这里.
  1. The file is not running in another application.
  2. The file is not in a protected folder.
  3. The file can be deleted manually with no problems and that's why i am 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拒绝访问该路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆