如何删除子目录

发布于 2024-09-11 12:51:06 字数 428 浏览 2 评论 0原文

假设有一些路径: C:\Temp\TestFolder1\TestFolder2

我有一些模板: C:\Temp

所以我想编写将通过模板删除所有子目录的函数

void DeleteSubdirectories(string tlt, string path) {}

如果我使用给定参数调用此函数

DeleteSubdirectories("C:\Temp", "C:\Temp\TestFolder1\TestFolder2");

它必须从 'TestFolder1\TestFolder2 子目录中删除>C:\Temp

编写此函数的最佳方法是什么?

Lets say a have some path:
C:\Temp\TestFolder1\TestFolder2

And I have some template:
C:\Temp

So I want to write function that will delete all subdirectories by template

void DeleteSubdirectories(string tlt, string path) {}

If I call this function with given parameters

DeleteSubdirectories("C:\Temp", "C:\Temp\TestFolder1\TestFolder2");

It must delete TestFolder1\TestFolder2 subdirectories from 'C:\Temp

What is the best way to write this function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

歌枕肩 2024-09-18 12:51:06

如果您也想删除“C:\Temp”,请使用以下命令:

System.IO.Directory.Delete(@"C:\Temp", true);

如果您只想删除子目录,请使用以下命令:

foreach (var subDir in new DirectoryInfo(@"C:\Temp").GetDirectories()) {
    subDir.Delete(true);
}

If you desire to delecte "C:\Temp" too, use this:

System.IO.Directory.Delete(@"C:\Temp", true);

If you just want to delete the sub directories use this:

foreach (var subDir in new DirectoryInfo(@"C:\Temp").GetDirectories()) {
    subDir.Delete(true);
}
椵侞 2024-09-18 12:51:06
System.IO.Directory.Delete("Path", true);
System.IO.Directory.Delete("Path", true);
扎心 2024-09-18 12:51:06

只需使用 Directory.Delete -我链接的重载有一个布尔值,指示是否也应删除子目录。

Just use Directory.Delete - the overload I linked has a boolean value that indicates if subdirectories should also be deleted.

愛放△進行李 2024-09-18 12:51:06

你所描述的听起来很奇怪,但是试试这个:

using System;
using System.IO;

static void DeleteSubDirectories(string rootDir, string childPath)
{
    string fullPath = Path.Combine(rootDir, childPath);

    Directory.Delete(fullPath);

    string nextPath = Path.GetDirectoryName(fullPath);

    while (nextPath != rootDir)
    {
        Directory.Delete(nextPath);
        nextPath = Path.GetDirectoryName(nextPath);
    }
}

使用它:

DeleteSubdirectories("C:\Temp", "TestFolder1\TestFolder2");

显然,你必须实现异常处理。

What you're describing sounds wierd, but try this:

using System;
using System.IO;

static void DeleteSubDirectories(string rootDir, string childPath)
{
    string fullPath = Path.Combine(rootDir, childPath);

    Directory.Delete(fullPath);

    string nextPath = Path.GetDirectoryName(fullPath);

    while (nextPath != rootDir)
    {
        Directory.Delete(nextPath);
        nextPath = Path.GetDirectoryName(nextPath);
    }
}

Use it like:

DeleteSubdirectories("C:\Temp", "TestFolder1\TestFolder2");

Obviously, you'll have to implement the exception handling.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文