C#Stackoverflow在递归删除目录操作中

时间:2010-07-02 21:32:29

标签: c# stack-overflow delete-file delete-directory

我目前正在使用安全删除算法和内容重写文件删除工具。 Wenn我正在尝试以递归方式浏览目录并删除其中的所有文件以及所有子目录等。调试器将抛出stackoverflow异常。

   private void wipeFile(string file)
   {
        bool ret = false;
        switch (m_algo)
        {
            case Algorithms.fastAlgo:
                ret = FastWipe.WipeFile(file);
                break;
            case Algorithms.safeAlgo:
                ret = CleanWipe.WipeFile(file, m_timesToWrite);
                break;
        }
        handleFileWiped(file, DateTime.Now, ret);
    }

    /// <summary>
    /// Wipes a directory recursively
    /// </summary>
    /// <param name="directory">Given subdir</param>
    private void deepWipe(string directory)
    {
        foreach (string file in Directory.GetFiles(directory))
        {
            wipeFile(file);
        }
        foreach (string subdir in Directory.GetDirectories(directory))
        {
            deepWipe(directory);
        }
        try
        {
            Directory.Delete(directory);
            handleDirectoryWiped(directory, DateTime.Now, true);
        }
        catch { handleDirectoryWiped(directory, DateTime.Now, false); }
    }

1 个答案:

答案 0 :(得分:3)

改变这个:

 foreach (string subdir in Directory.GetDirectories(directory))
 {
     deepWipe(directory);
 }

为:

 foreach (string subdir in Directory.GetDirectories(directory))
 {
     deepWipe(subdir);
 }