0

Possible Duplicate:
How do I get a directory size (files in the directory) in C#?

I have a program which makes SQL Server backups. After every run it creates a backup file. But the files are accumulating.

I´d like to add method which will be checking the backup directory size and if the size will be higher then threshold size, it will delete last file.

Do you know how can I do this?

Thanks a lot!

Community
  • 1
  • 1
VilemRousi
  • 2,082
  • 4
  • 24
  • 34

2 Answers2

1

Using DirectoryInfo and a bit of Linq is an easy task

public void RemoveLastFile(string folderPath, long dirSizeLimit)
{
    long size = 0;
    var files = new DirectoryInfo(folderPath).GetFiles();
    files.Sum(f => size += f.Length);
    if(size > dirSizeLimit)
    {
       var sorted = files.OrderBy(f => f.LastWriteTime);
       File.Delete(sorted.First().FullName);
   }
}

of course this is an example. You need to add a bit of error checking.
P.S. I have use the property LastWriteTime of the FileInfo class, in your case (backup files) I think that it is equivalent to CreationTime.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • This is really simple answer. I'd just replace `if` loop with `while`, having in mind that several files could be created between consecutive calls to `RemoveLastFile`. – Nikola Malešević Sep 02 '12 at 22:16
0

Add all the files in list and use CompareTo in combination with FileInfo CreationTime to sort the list. Then delete the files accordingly based on how many files you want to stay in the directory.

As for calculating the directory file simply iterate through all the files in the directory while using FileInfo Length to increment a variable for the total size.

coolmine
  • 4,427
  • 2
  • 33
  • 45