2016-08-03 77 views
0

我有一个程序需要删除一个完整的目录,但我得到了Access to path denied错误。我给予每个人完全的访问权限,但它没有帮助。访问路径被拒绝错误

private void timer1_Tick(object sender, EventArgs e) 
{ 
    label1.Text = DateTime.Now.ToString("HH:mm"); 
    string lowDir = ""; 
    if (label1.Text == comboBox1.Text) 
    { 
     try 
     { 
      if (System.IO.Directory.GetDirectories(txpath1.Text).Length != 0) 
      { 
       try 
       { 
        var folders = Directory.GetDirectories(@"" + txpath1.Text); 
        DateTime lastLow = DateTime.Now; 

        foreach (string subdir in Directory.GetDirectories(@"" + txpath1.Text)) 
        { 
         DirectoryInfo fi1 = new DirectoryInfo(subdir); 
         fi1.Refresh(); 
         DateTime created = fi1.LastWriteTime; 
         if (created < lastLow) 
         { 
          lowDir = subdir; 
          lastLow = created; 
         } 
        } 
        var dir = new DirectoryInfo(@"" + lowDir); 
        Directory.Delete(@"" + lowDir, true); 
       } 
       catch (Exception ex) 
       { 
        this.btStop.PerformClick(); 
        MessageBox.Show(ex.Message+"\nEzért a program leállt."); 
       } 
       finally 
       { 
        timer1.Stop(); 
        timer2.Start(); 
       } 
      } 
      else 
      { 
       this.btStop.PerformClick(); 
       MessageBox.Show("A megadott elérési útvonalon nem találhatóak fájlok a művelet(ek)hez!"); 
      } 
     } 
     catch (DirectoryNotFoundException) 
     { 
      btStop.PerformClick(); 
      MessageBox.Show("Hibás útvonala(kat)t adtál meg!"); 
     } 
    } 
} 
+1

在尝试删除目录之前是否检查该目录是空的?并确保目录不是只读 – Josh

+0

我不确定你是否正确地转义'txpath1.Text'。 – user1666620

+0

乔希,不,我现在没有检查它,我可以使它工作后,我会。该目录不是空的,通常当目录包含mp3,mp4或exe文件时,我得到这个错误。如果我将一个简单的pdf文件放入该目录中,我不会收到此错误。 – celodir

回答

0

您只需要使用Directory.Delete(path, true)递归删除。如果这不起作用,那么它可能是一个格格不入的路径。