C#フォルダーとそのフォルダー内のすべてのファイルとフォルダーを削除する


104

フォルダーとそのフォルダー内のすべてのファイルとフォルダーを削除しようとしています。以下のコードを使用していますが、エラーが表示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);
}

回答:



110

マニュアルを読む:

Directory.Deleteメソッド(文字列、ブール)

Directory.Delete(folderPath, true);

68
それをググググしてここに行くのがはるかに速いときにマニュアルを読むのはなぜですか?
レゲエギター2015年

5
これは本当です
コルビン

4
確かに...これをググっただけで、この投稿はグーグルからの最初の結果でした。
MasterN8 2018年

2
私が時々していることは、質問をしてから自分で答えて、将来のグーグルを助けることです。StackOverflowでは、質問と回答を同時に投稿できます。
DharmaTurtle

1
私は地元のすべての文書をこのようにして始めました。よくある質問ではなく、SOの質問のようです。つまり、どうすればよいですか?またはこれは何ですか?
Paul Duer

23

試してください:

System.IO.Directory.Delete(path,true)

これにより、「パス」の下にあるすべてのファイルとフォルダーが再帰的に削除されます。





3

これを試して。

namespace EraseJunkFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\somedirectory\");
            foreach (DirectoryInfo dir in yourRootDir.GetDirectories())
                    DeleteDirectory(dir.FullName, true);
        }
        public static void DeleteDirectory(string directoryName, bool checkDirectiryExist)
        {
            if (Directory.Exists(directoryName))
                Directory.Delete(directoryName, true);
            else if (checkDirectiryExist)
                throw new SystemException("Directory you want to delete is not exist");
        }
    }
}

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);
    }
}

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.

このコードは質問に答えることがありますが、問題を解決する方法および/または理由に関する追加のコンテキストを提供すると、回答の長期的な価値が向上します。これを読む
Shanteshwar Inde

0

DirectoryNotFoundExceptionが発生した場合は、次のチェックを追加してください。

if (Directory.Exists(path)) Directory.Delete(path, true);
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.