-2

I created a service which will move backup to a disk on daily basis.

But before moving the backup i need to check the available space of the disk. If available space is less than 1 TB need to delete the oldest backup folder from the disk and then continue the backup

I got the available space using below code

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

Now i need to check FreeSpace value is less than 1

if(FreeSpace < 1)
{

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

eg:-

 > 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

How to achive the same in C#

Sachu
  • 7,555
  • 7
  • 55
  • 94
  • Why the down vote ?? – Sachu Jun 22 '17 at 05:42
  • I think using the folder name which is a date is best method : DirectoryInfo info = new DirectoryInfo("folder").GetDirectories().AsEnumerable().OrderBy(x => DateTime.Parse(x.Name)).LastOrDefault(); info.Delete(); – jdweng Jun 22 '17 at 05:45
  • 1
    Half of your post is unrelated to your question. The calculation for free space has nothing to do with finding the folder to delete. Your question is really "How do I enumerate and sort folders by name?" Of which you'd find plenty of examples if you'd search. – Rob Jun 22 '17 at 05:57

3 Answers3

2

Have you tried this:

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

Now you will have the DirectoryInfo object of the first folder in directory, You can proceed with delete option as like this:

foreach(System.IO.FileInfo file in directory.GetFiles()) file.Delete();
foreach(System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
2

you can delete by following way.

FileSystemInfo fileInfo = new DirectoryInfo("H://backup").GetFileSystemInfos().OrderByDescending(fi => fi.CreationTime).First();
Directory.Delete(fileInfo.FullName,true);
Pranav Patel
  • 1,541
  • 14
  • 28
  • Thanks it working fine. Only change is 'OrderByDescending' not needed that will delete the latest folder. Need to delete the oldest one. So 'OrderBy' – Sachu Jun 22 '17 at 05:52
0

Several options:

The FileSystemInfo class. Here's a line of code to file the oldest in a directory:

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

You'll have to make this recursive somehow. There's also a thread on how to get all files in a disk

RoundSauce3
  • 170
  • 1
  • 16