简体   繁体   English

拒绝访问路径被拒绝-Winform C#

[英]Access denied to the path is denied - Winform C#

I am creating browser cleaner software and i am trying clear the all the cache files in the directory 我正在创建浏览器清洁器软件,并且尝试清除目录中的所有缓存文件

C:\\Users\\RamRo\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cache C:\\ Users \\ RamRo \\ AppData \\ Local \\ Google \\ Chrome \\ User Data \\ Default \\ Cache

I am using this code to delete the files but trying to delete this 我正在使用此代码删除文件,但尝试删除此文件

private void button3_Click(object sender, EventArgs e)
{
    System.IO.DirectoryInfo di = new DirectoryInfo(@"C:\Users\RamRo\AppData\Local\Google\Chrome\User Data\Default\Cache");

    foreach (FileInfo file in di.GetFiles())
    {
        file.Delete();
    }
    foreach (DirectoryInfo dir in di.GetDirectories())
    {
        dir.Delete(true);
    }
}

But when i try to execute this program struggling with this issue 但是当我尝试执行此程序时遇到这个问题 在此处输入图片说明

Well, almost certainly the answer is that the file is in use. 好吧,几乎可以肯定的答案是该文件正在使用中。 The cache is used after all! 毕竟使用缓存! With respect to deleting folders, that will fail if the folders contains any files or subfolders. 关于删除文件夹,如果文件夹包含任何文件或子文件夹,将失败。

Any code that performs this task will have to deal with potential errors, and should graciously handle any errors trying to delete such files. 任何执行此任务的代码都必须处理潜在的错误,并且应优雅地处理试图删除此类文件的任何错误。 You should read about try...catch . 您应该阅读有关try...catch

With respect to both previous answers, your code should probably look something like this: 关于前面的两个答案,您的代码应该看起来像这样:

private void button3_Click(object sender, EventArgs e)
{              
    System.IO.DirectoryInfo di = new DirectoryInfo(@"C:\Users\RamRo\AppData\Local\Google\Chrome\User Data\Default\Cache");
    List<FileSystemInfo> notDeletable = new List<FileSystemInfo>();    

    foreach (FileInfo file in di.GetFiles())
    {
      try 
      {
        file.Delete();
      }
      catch (Exception ex)
      {
        notDeletable.Add(file);
      }
    }
    foreach (DirectoryInfo dir in di.GetDirectories())
    {
      try
      {
        dir.Delete(true);
      }
      catch (Exception ex)
      {
        notDeletable.Add(dir);
      }
    }
    // Process 'notDeletable' List
}

Maybe you should even make the Directory part recursive... 也许您甚至应该使目录部分递归...

Do this instead: 改为这样做:

try
{
    file.Delete();
}
catch(Exception){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM