【问题标题】:How to delete oldest folder created from local disk using C#如何使用 C# 删除从本地磁盘创建的最旧文件夹
【发布时间】:2017-11-25 05:26:04
【问题描述】:

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

但在移动备份之前,我需要检查磁盘的可用空间。 如果可用空间小于 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# 中实现相同的目标

【问题讨论】:

  • 为什么投反对票??
  • 我认为使用作为日期的文件夹名称是最好的方法: DirectoryInfo info = new DirectoryInfo("folder").GetDirectories().AsEnumerable().OrderBy(x => DateTime.Parse( x.Name)).L​​astOrDefault(); info.Delete();
  • 您的帖子有一半与您的问题无关。可用空间的计算与查找要删除的文件夹无关。您的问题实际上是“如何按名称枚举和排序文件夹?”如果你搜索一下,你会找到很多例子。

标签: c# .net


【解决方案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】:

    您可以通过以下方式删除。

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

    【讨论】:

    • 感谢它工作正常。唯一的改变是不需要'OrderByDescending',它将删除最新的文件夹。需要删除最旧的。所以'OrderBy'
    【解决方案3】:

    几个选项:

    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

    【讨论】:

    • 支持这项工作
    猜你喜欢
    • 1970-01-01
    • 2012-10-17
    • 2012-05-23
    • 2019-01-14
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多