C# Function To Delete Temporary Files Older Than 7 Days using LINQ


With C#, we can write code in a quick and elegant way. For example, if you want to search for temporary files (with some file patterns) in the system temporary folder, and only delete those that are older than 7 days, you could use the LINQ.

c-sharp-delete-function-temporary-files C# Function To Delete Temporary Files Older Than 7 Days using LINQ c # code code library I/O File implementation programming languages

C# static function to delete files that are older than 7 days

The idea is to search all files and check their file timestamps. The following C# static function has two parameters but both can be omitted by using its default values. The first parameter daysAgo specifies the files’s age for deletion and the parameter maxToDelete sets a maximum number for deletion (i.e. You could set up a background crontab that runs every hour and delete 10 files each time). If folder contains quite a number of temporary files, the deletion process takes time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static void DeleteTempFiles(int daysAgo = 7, int maxToDelete = 10)
{
    string tempDir = Path.GetTempPath();
    string[] files = Directory.GetFiles(tempDir, "tmp*.tmp", SearchOption.TopDirectoryOnly);
    if (files.Length > 0)
    {
        string[] filesToDelete = files.Where(c =>
        {
            TimeSpan ts = DateTime.Now - File.GetLastAccessTime(c);
            return (ts.Days > daysAgo);
        }).ToArray();
        for (int i = 0; i < Math.Min(filesToDelete.Length, maxToDelete); i++)
        {
            File.Delete(filesToDelete[i]);
        }
    }
}
public static void DeleteTempFiles(int daysAgo = 7, int maxToDelete = 10)
{
    string tempDir = Path.GetTempPath();
    string[] files = Directory.GetFiles(tempDir, "tmp*.tmp", SearchOption.TopDirectoryOnly);
    if (files.Length > 0)
    {
        string[] filesToDelete = files.Where(c =>
        {
            TimeSpan ts = DateTime.Now - File.GetLastAccessTime(c);
            return (ts.Days > daysAgo);
        }).ToArray();
        for (int i = 0; i < Math.Min(filesToDelete.Length, maxToDelete); i++)
        {
            File.Delete(filesToDelete[i]);
        }
    }
}

The file patten is hard-coded as tmp*.tmp which is the default pattern for temporary files on Windows. Change this to suit your needs. In order for above code to work, you would also need the use the namespaces System.IO and System.Linq.

--EOF (The Ultimate Computing & Technology Blog) --

GD Star Rating
loading...
349 words
Last Post: SEO Ranking Signal - Use VPS or Dedicated Server over Share Hosts
Next Post: C++ Coding Exercise - Triangle - Leetcode Online Judge - O(n) Dynamic Programming Optimisation

The Permanent URL is: C# Function To Delete Temporary Files Older Than 7 Days using LINQ

Leave a Reply