我正在尝试删除存储卡上的所有文件,而不删除其中一个。我可以用当前代码保留我指定的目录,但不能保留其内容。它只是留下空白文件夹数据,因为它删除了里面的所有内容。如何防止它删除该文件夹及其内容?
private void button1_Click(object sender, EventArgs e)
{
ScanDirectory scanDirectory = new ScanDirectory();
scanDirectory.WalkDirectory(@"/Storage Card");
scanDirectory.WalkDirectory(@"/Application");
}
public class ScanDirectory
{
public void WalkDirectory(string directory)
{
WalkDirectory(new DirectoryInfo(directory));
}
private static void WalkDirectory(DirectoryInfo directory)
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
var name = file.Name;
name = name.ToLower();
if (name != "test.txt")
{
file.Delete();
}
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
var name = subDirectory.Name;
name = name.ToLower();
if (name != "data")
{
subDirectory.Delete();
}
}
}
}
问题在于递归函数调用的方式:主函数private static void WalkDirectory(DirectoryInfo directory)
删除所有文件,并且每次都被调用(甚至在分析子目录时)。在这里,您有一个修复程序,可以使此代码按您的意愿工作:
private static void WalkDirectory(DirectoryInfo directory)
{
if (directory.Name.ToLower() != "data")
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
var name = file.Name;
name = name.ToLower();
if (name != "test.txt")
{
file.Delete();
}
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
var name = subDirectory.Name;
name = name.ToLower();
if (name != "data")
{
subDirectory.Delete();
}
}
}
}
private static void WalkDirectory(DirectoryInfo directory)
{
if (directory.Name.ToLower() != "data")
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
var name = file.Name;
name = name.ToLower();
if (name != "test.txt")
{
file.Delete();
}
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
var name = subDirectory.Name;
name = name.ToLower();
if (name != "data")
{
subDirectory.Delete();
}
}
}
}