帝天龙 發表於 2025-12-29 08:48:24

C#删除文件夹里的所有文件的实现方案

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>一、 基础方案:删除文件夹内所有文件(保留子文件夹)</li><ul class="second_class_ul"><li>核心 API 说明</li><li>实现代码</li></ul><li>二、 进阶方案 1:删除文件夹内所有文件(包含子文件夹文件)</li><ul class="second_class_ul"><li>核心 API 说明</li><li>实现代码</li></ul><li>三、 进阶方案 2:删除文件夹(含所有文件 + 子文件夹)+ 重建空文件夹</li><ul class="second_class_ul"><li>核心 API 说明</li><li>实现代码</li></ul><li>四、 关键注意事项(避坑指南)</li><ul class="second_class_ul"></ul><li>总结</li><ul class="second_class_ul"></ul></ul></div><p class="maodian"></p><h2>一、 基础方案:删除文件夹内所有文件(保留子文件夹)</h2>
<p>适用于仅删除目标文件夹下<strong>直接存放的文件</strong>,不删除子文件夹及其内部文件的场景,核心使用&nbsp;<code>System.IO</code>&nbsp;命名空间的 API。</p>
<p class="maodian"></p><p class="maodian"></p><p class="maodian"></p><h3>核心 API 说明</h3>
<ol><li><code>Directory.GetFiles(string path)</code>:获取指定文件夹下所有直接文件的完整路径(返回&nbsp;<code>string[]</code>&nbsp;数组)。</li><li><code>File.Delete(string filePath)</code>:删除单个指定文件,需处理文件占用等异常。</li></ol>
<p class="maodian"></p><p class="maodian"></p><p class="maodian"></p><h3>实现代码</h3>
<div class="jb51code"><pre class="brush:csharp;">using System;
using System.IO;

namespace DeleteFolderFiles
{
    class BasicDelete
    {
      /// &lt;summary&gt;
      /// 删除指定文件夹内所有直接文件(保留子文件夹)
      /// &lt;/summary&gt;
      /// &lt;param name="folderPath"&gt;目标文件夹路径&lt;/param&gt;
      public static void DeleteAllFilesInFolder(string folderPath)
      {
            // 1. 验证文件夹是否存在,避免路径错误
            if (!Directory.Exists(folderPath))
            {
                Console.WriteLine($"错误:文件夹 {folderPath} 不存在!");
                return;
            }

            try
            {
                // 2. 获取文件夹内所有直接文件的路径
                string[] allFiles = Directory.GetFiles(folderPath);

                // 3. 遍历并删除每个文件
                foreach (string filePath in allFiles)
                {
                  // 确保文件存在(避免并发场景下文件已被删除)
                  if (File.Exists(filePath))
                  {
                        File.Delete(filePath);
                        Console.WriteLine($"成功删除文件:{filePath}");
                  }
                }

                Console.WriteLine("所有文件删除完成!");
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine($"错误:没有权限删除文件 - {ex.Message}");
            }
            catch (IOException ex)
            {
                Console.WriteLine($"错误:文件被占用或无法删除 - {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"未知错误:{ex.Message}");
            }
      }

      // 调用示例
      static void Main(string[] args)
      {
            // 目标文件夹路径(可改为绝对路径,如 @"D:\TestFolder")
            string targetFolder = @"TestFolder";
            DeleteAllFilesInFolder(targetFolder);
      }
    }
}</pre></div>
<p class="maodian"></p><h2>二、 进阶方案 1:删除文件夹内所有文件(包含子文件夹文件)</h2>
<p>适用于需要递归删除<strong>目标文件夹下所有文件(含子文件夹内文件)</strong>,仅保留文件夹结构(不删除任何文件夹)的场景。</p>
<h3>核心 API 说明</h3>
<p><code>Directory.GetFiles(string path, string searchPattern, SearchOption searchOption)</code>:</p>
<ul><li><code>searchPattern</code>:文件筛选模式,<code>&quot;*.*&quot;</code>&nbsp;匹配所有文件。</li><li><code>SearchOption.AllDirectories</code>:递归搜索所有子目录(<code>TopDirectoryOnly</code>&nbsp;仅搜索当前目录,对应基础方案)。</li></ul>
<h3>实现代码</h3>
<div class="jb51code"><pre class="brush:csharp;">using System;
using System.IO;

namespace DeleteFolderFiles
{
    class RecursiveDeleteFiles
    {
      /// &lt;summary&gt;
      /// 递归删除文件夹内所有文件(包含子文件夹文件,保留文件夹结构)
      /// &lt;/summary&gt;
      /// &lt;param name="folderPath"&gt;目标文件夹路径&lt;/param&gt;
      public static void DeleteAllFilesRecursively(string folderPath)
      {
            if (!Directory.Exists(folderPath))
            {
                Console.WriteLine($"错误:文件夹 {folderPath} 不存在!");
                return;
            }

            try
            {
                // 递归获取所有文件(当前目录+所有子目录)
                string[] allFiles = Directory.GetFiles(
                  folderPath,
                  "*.*",
                  SearchOption.AllDirectories
                );

                // 批量删除
                foreach (string filePath in allFiles)
                {
                  if (File.Exists(filePath))
                  {
                        // 可选:设置文件为正常属性(避免只读文件无法删除)
                        File.SetAttributes(filePath, FileAttributes.Normal);
                        File.Delete(filePath);
                        Console.WriteLine($"成功删除文件:{filePath}");
                  }
                }

                Console.WriteLine("所有文件(含子文件夹文件)删除完成!");
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine($"权限错误:{ex.Message}");
            }
            catch (IOException ex)
            {
                Console.WriteLine($"文件占用错误:{ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"未知错误:{ex.Message}");
            }
      }

      // 调用示例
      static void Main(string[] args)
      {
            string targetFolder = @"D:\TestFolder";
            DeleteAllFilesRecursively(targetFolder);
      }
    }
}</pre></div>
<p class="maodian"></p><h2>三、 进阶方案 2:删除文件夹(含所有文件 + 子文件夹)+ 重建空文件夹</h2>
<p>适用于需要彻底清空文件夹(删除所有文件和子文件夹),最终保留一个空的目标文件夹的场景,比递归删除文件更高效。</p>
<h3>核心 API 说明</h3>
<ol><li><code>Directory.Delete(string path, bool recursive)</code>:
<ul><li><code>recursive: true</code>:递归删除目标文件夹及其所有子文件夹、文件。</li><li><code>recursive: false</code>:仅删除空的目标文件夹。</li></ul></li><li><code>Directory.CreateDirectory(string path)</code>:创建文件夹(若文件夹已存在,不会抛出异常,直接返回现有文件夹信息)。</li></ol>
<h3>实现代码</h3>
<div class="jb51code"><pre class="brush:csharp;">using System;
using System.IO;

namespace DeleteFolderFiles
{
    class DeleteAndRecreateFolder
    {
      /// &lt;summary&gt;
      /// 彻底清空文件夹(删除文件+子文件夹),重建空文件夹
      /// &lt;/summary&gt;
      /// &lt;param name="folderPath"&gt;目标文件夹路径&lt;/param&gt;
      public static void ClearFolderCompletely(string folderPath)
      {
            try
            {
                // 1. 若文件夹存在,递归删除(含所有文件和子文件夹)
                if (Directory.Exists(folderPath))
                {
                  Directory.Delete(folderPath, true);
                  Console.WriteLine($"已删除文件夹:{folderPath}");
                }

                // 2. 重建空文件夹
                Directory.CreateDirectory(folderPath);
                Console.WriteLine($"已重建空文件夹:{folderPath}");
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine($"权限错误:无法删除/创建文件夹 - {ex.Message}");
            }
            catch (IOException ex)
            {
                Console.WriteLine($"IO错误:文件夹被占用 - {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"未知错误:{ex.Message}");
            }
      }

      // 调用示例
      static void Main(string[] args)
      {
            string targetFolder = @"D:\TestFolder";
            ClearFolderCompletely(targetFolder);
      }
    }
}</pre></div>
<p class="maodian"></p><h2>四、 关键注意事项(避坑指南)</h2>
<ol><li><strong>路径格式</strong>:
<ul><li>C# 中文件夹路径推荐使用&nbsp;<code>@</code>&nbsp;Verbatim 字符串(如&nbsp;<code>@&quot;D:\TestFolder&quot;</code>),避免转义字符(<code>\</code>)冲突。</li><li>支持相对路径(如&nbsp;<code>@&quot;TestFolder&quot;</code>)和绝对路径(如&nbsp;<code>@&quot;D:\TestFolder&quot;</code>),相对路径对应程序运行目录。</li></ul></li><li><strong>异常处理</strong>:<ul><li>必须捕获&nbsp;<code>UnauthorizedAccessException</code>(权限不足)和&nbsp;<code>IOException</code>(文件 / 文件夹被占用、只读文件等)。</li><li>避免因单个文件删除失败导致整个批量操作中断(可在循环内添加&nbsp;<code>try-catch</code>&nbsp;单独处理单个文件)。</li></ul></li><li><strong>只读文件处理</strong>:<ul><li>若文件为「只读属性」,直接调用&nbsp;<code>File.Delete</code>&nbsp;会抛出异常,需先通过&nbsp;<code>File.SetAttributes(filePath, FileAttributes.Normal)</code>&nbsp;重置文件属性。</li></ul></li><li><strong>并发安全</strong>:<ul><li>若存在多线程 / 多进程操作同一文件夹,需先通过&nbsp;<code>File.Exists(filePath)</code>&nbsp;验证文件是否存在,避免删除已被其他进程删除的文件。</li></ul></li><li><strong>谨慎操作</strong>:<ul><li>删除操作不可逆,建议在正式删除前添加日志输出或备份逻辑,避免误删重要文件。</li><li>切勿操作系统关键文件夹(如&nbsp;<code>C:\Windows</code>),可能导致系统异常。</li></ul></li></ol>
<p class="maodian"></p><h2>总结</h2>
<ol><li><strong>仅删当前文件夹文件(保留子文件夹)</strong>:使用&nbsp;<code>Directory.GetFiles(folderPath)</code>&nbsp;+ 遍历&nbsp;<code>File.Delete</code>。</li><li><strong>删所有文件(含子文件夹文件,保留文件夹结构)</strong>:使用&nbsp;<code>Directory.GetFiles(..., SearchOption.AllDirectories)</code>&nbsp;+ 递归删除。</li><li><strong>彻底清空文件夹(重建空文件夹)</strong>:使用&nbsp;<code>Directory.Delete(folderPath, true)</code>&nbsp;+&nbsp;<code>Directory.CreateDirectory(folderPath)</code>,效率最高。</li><li><strong>安全要点</strong>:添加异常处理、验证路径存在、处理只读文件、避免误删系统文件。</li></ol>
<p>到此这篇关于C#删除文件夹里的所有文件的实现方案的文章就介绍到这了,更多相关C#删除文件夹所有文件内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>C#判断文件夹是否存在,并执行删除、创建操作方式</li><li>C#如何删除指定文件或文件夹</li><li>C#实现文件夹的复制和删除</li><li>c#删除指定文件夹中今天之前的文件</li><li>C#删除只读文件或文件夹(解决File.Delete无法删除文件)</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: C#删除文件夹里的所有文件的实现方案