删除文件的正确方法&里面的目录,但单独留下目录路径?

时间:2015-10-06 14:54:47

标签: c#

在下面的脚本中,我想保留" Dominion"文件夹没有被删除。问题是这个Directory.Delete命令删除了" Dominion"文件夹中。

var directoryPath = "X:\Applications\Dealer\Data\Ftp\Incoming";

if (Directory.Exists(directoryPath + @"\" + "Dominion"))  
{
    Directory.Delete(directoryPath + @"\" + "Dominion", true);
}
Directory.CreateDirectory(directoryPath + @"\" + "Dominion");  

3 个答案:

答案 0 :(得分:2)

你可以使用这种方法:

var root = new DirectoryInfo(@"X:\Applications\Dealer\Data\Ftp\Incoming");
var deleteableEntries = root.EnumerateFileSystemInfos()
    .Where(entry => (entry.Attributes & FileAttributes.Directory) != FileAttributes.Directory || entry.Name != "Dominion");
foreach(var entryToDelete in deleteableEntries)
    entryToDelete.Delete();

由于这会因为几个原因(访问被拒绝或文件夹没有空)而失败,所以这是一个相当未经测试的方法,它应该起作用或至少给出一个想法:

var stack = new Stack<FileSystemInfo>(deleteableEntries); // "recursive", stack to delete deepest folders first

while (stack.Count > 0)
{
    FileSystemInfo fsi = stack.Peek();  // don't remove yet, only if it was deleted
    bool isDirectory = (fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory;
    fsi.Attributes = FileAttributes.Normal; // can avoid possible access-denied exceptions if it's readonly
    try
    {
        bool canBeDeleted = !isDirectory;
        if (isDirectory)
        {
            var subEntries = new DirectoryInfo(fsi.FullName).EnumerateFileSystemInfos("*.*", SearchOption.AllDirectories);
            canBeDeleted = !subEntries.Any();
            foreach (FileSystemInfo subEntry in subEntries)
                stack.Push(subEntry);
        }
        if (canBeDeleted)
        {
            fsi.Delete();
            stack.Pop(); // remove it
        }
    } catch (Exception ex)
    {
        Console.Error.WriteLine(ex);
    }
}

答案 1 :(得分:1)

请使用:

var directoryPath = @"X:\Applications\Dealer\Data\Ftp\Incoming";
System.IO.DirectoryInfo directoryToClean = new DirectoryInfo(directoryPath );

foreach (FileInfo file in directoryToClean.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in directoryToClean.GetDirectories().Where(dir => dir.Name != "Dominion"))
{
    dir.Delete(true);
}

答案 2 :(得分:1)

您可以将此简化为委托,但获取文件并循环遍历它们非常简单。

var directoryPath = "X:\Applications\Dealer\Data\Ftp\Incoming";

if (Directory.Exists(directoryPath + @"\" + "Dominion"))  
{
    var newPath = directoryPath + @"\" + "Dominion";
    var files = Directory.GetAllFiles(newPath);

    foreach (var file in files)
    {
        File.Delete(file);
    }
}