如何使用C#删除从本地磁盘创建的最旧文件夹

时间:2017-06-22 05:28:31

标签: c# .net

我创建了一项服务,每天都会将备份移动到磁盘上。

但在移动备份之前,我需要检查磁盘的可用空间。 如果可用空间小于1 TB,则需要从磁盘中删除最旧的备份文件夹,然后继续备份

我使用以下代码获得了可用空间

DriveInfo driveInfo = new DriveInfo(@"H:");
long FreeSpace = (((driveInfo.AvailableFreeSpace) / 1024) / 1024 / 1024) / 1024;

现在我需要检查FreeSpace值是否小于1

if(FreeSpace < 1)
{

  //need to delete the folder in the path H:\backup\
  //whose created date is the oldest
}

例如: -

 > If available space is less than 1 TB and H:\backup\ contain 3 folder
    > 19062017   -- created on 19/06/2017 
      20062017   -- created on 20/06/2017 
      21062017   -- created on 21/06/2017

    > We need to delete the folder 19062017 with its content

如何在C#中实现相同功能

3 个答案:

答案 0 :(得分:2)

您可以按照以下方式删除。

FileSystemInfo fileInfo = new DirectoryInfo("H://backup").GetFileSystemInfos().OrderBy(fi => fi.CreationTime).First();
Directory.Delete(fileInfo.FullName,true);

答案 1 :(得分:1)

你试过这个:

var infoDir = new DirectoryInfo(@"H:\backup");
var directory = di.EnumerateDirectories() 
                    .OrderBy(d => d.CreationTime)
                    .First();

现在您将拥有directory中第一个文件夹的DirectoryInfo对象,您可以像这样继续删除选项:

foreach(System.IO.FileInfo file in directory.GetFiles()) file.Delete();
foreach(System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);

答案 2 :(得分:1)

有几个选择:

FileSystemInfo类。这是一行代码,用于存档目录中最早的代码:

FileSystemInfo fileInfo = new DirectoryInfo(directoryPath).GetFileSystemInfos()
.OrderByDescending(fi => fi.CreationTime).First();

你必须以某种方式使这个递归。 There's also a thread on how to get all files in a disk