我正在尝试删除该文件夹以及该文件夹中的所有文件和文件夹,我正在使用下面的代码并收到错误Folder is not empty
,有关我可以做什么的建议吗?
try
{
var dir = new DirectoryInfo(@FolderPath);
dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
dir.Delete();
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i].Index);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
答案 0 :(得分:128)
dir.Delete(true); // true => recursive delete
答案 1 :(得分:79)
答案 2 :(得分:22)
尝试:
System.IO.Directory.Delete(path,true)
这将以递归方式删除“path”下的所有文件和文件夹,假设您有权这样做。
答案 3 :(得分:6)
呃,怎么样只是打电话给Directory.Delete(path, true);
?
答案 4 :(得分:4)
Directory.Delete方法有一个递归的布尔参数,它应该做你需要的
答案 5 :(得分:3)
答案 6 :(得分:2)
试试这个。
True
答案 7 :(得分:2)
对于那些遇到DirectoryNotFoundException的人,请添加以下检查:
if (Directory.Exists(path)) Directory.Delete(path, true);
答案 8 :(得分:0)
public void Empty(System.IO.DirectoryInfo directory)
{
try
{
logger.DebugFormat("Empty directory {0}", directory.FullName);
foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}
catch (Exception ex)
{
ex.Data.Add("directory", Convert.ToString(directory.FullName, CultureInfo.InvariantCulture));
throw new Exception(string.Format(CultureInfo.InvariantCulture,"Method:{0}", ex.TargetSite), ex);
}
}
答案 9 :(得分:0)
尝试一下:
foreach (string files in Directory.GetFiles(SourcePath))
{
FileInfo fileInfo = new FileInfo(files);
fileInfo.Delete(); //delete the files first.
}
Directory.Delete(SourcePath);// delete the directory as it is empty now.