2010-07-27 148 views
1

比方说,一个有一些路径: C:\ TEMP \ TestFolder1 \ TestFolder2如何删除子目录

而且我有一些模板: C:\ TEMP

所以我想写功能。如果我把这个功能给定参数

0123将由模板

void DeleteSubdirectories(string tlt, string path) {} 

删除所有子目录

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

必须删除TestFolder1 \ TestFolder2从“Ç子目录:\ TEMP

什么是写这个功能的最佳方式?

回答

2
System.IO.Directory.Delete("Path", true); 
+0

如果我这样称呼这个方法: Directory.Delete(@“C:\ Temp \ TestFolder1 \ TestFolder2”,true); 它只会被删除** TestFolder2 ** 我不想从Temp文件夹和Temp文件夹本身中删除所有子目录。我只想删除Path参数中的文件夹。在这种情况下:** TestFolder1 \ TestFolder2 ** – 2010-07-27 09:21:05

+0

@Alex,请原谅我,我不明白你的意思。无论如何,如果你想从'Temp'中删除'TestFolder1',你必须使用'System.IO.Directory.Delete(@“C:\ Temp \ TestFolder1”,true);''删除所需的目录及其目录子目录也是如此。 – 2010-07-27 10:19:08

1

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

4

如果您希望delecte “C:\ TEMP” 也使用此:

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

如果你只是想删除目录使用此子:

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

你是什么描述的声音奇怪,但试试这个:

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

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