這是一個遞歸函數,它將刪除給定目錄中的所有文件並向下瀏覽目錄結構。可以提供模式字符串,以便只對給定擴展名的文件起作用,就像您對其他答案的評論一樣。
Action<string,string> fileDeleter = null;
fileDeleter = (directoryPath, pattern) =>
{
string[] files;
if (!string.IsNullOrEmpty(pattern))
files = Directory.GetFiles(directoryPath, pattern);
else
files = Directory.GetFiles(directoryPath);
foreach (string file in files)
{
File.Delete(file);
}
string[] directories = Directory.GetDirectories(directoryPath);
foreach (string dir in directories)
fileDeleter(dir, pattern);
};
string path = @"C:\some_folder\";
fileDeleter(path, "*.bmp");
目錄以其它方式單獨留下,這顯然可以以與陣列或字符串列表使用具有多個初始目錄路徑工作。
以下是與標準函數相同的代碼,也將遞歸作爲參數選項。
public void DeleteFilesFromDirectory(string directoryPath, string pattern, bool includeSubdirectories)
{
string[] files;
if (!string.IsNullOrEmpty(pattern))
files = Directory.GetFiles(directoryPath, pattern);
else
files = Directory.GetFiles(directoryPath);
foreach (string file in files)
{
File.Delete(file);
}
if (includeSubdirectories)
{
string[] directories = Directory.GetDirectories(directoryPath);
foreach (string dir in directories)
DeleteFilesFromDirectory(dir, pattern, includeSubdirectories);
}
}
你是什麼意思「添加目錄到它」? – logicnp 2010-06-02 03:09:43