2

I'm trying to delete files in a directory that are older than 10 days, based on the "Last Modified Date". What it should do is take the input from a moxiemanager upload, which it does, and input that into the database, which it does. It should then delete files older than 10 days, which it doesn't. The following is my code:

public ActionResult CreateMain(BulletinsViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        BulletinsContext.tblBulletins.Add(new tblBulletin
        {
            ID = viewModel.BulletinID,
            BulletinDisplayDate = viewModel.BulletinDisplayDate,
            BulletinFilename = viewModel.MainBulletinName
        });

        DirectoryInfo DI = new DirectoryInfo(Server.MapPath("~/Files/Bulletins"));
        FileSystemInfo[] FSI = DI.GetFiles();
        foreach (FileSystemInfo fInfo in FSI)
        {
            if (fInfo.Extension == ".pdf")
            {
                DateTime dt = DateTime.Now.AddDays(-10);
                if (fInfo.CreationTime < dt)
                    try
                    {
                        fInfo.Delete();
                    }
                    catch { }
                }
            }
            BulletinsContext.SaveChanges();
            return RedirectToAction("MainBulletins");
        }

    return View(viewModel);
}

I'm thinking possibly that it may be either the filepath isn't the correct syntax for this method, or the "fInfo.CreationTime" section is wrong, but I feel like CreationTime would be last modified?

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
South Wilts
  • 121
  • 1
  • 14
  • 1
    You're discarding exceptions, are you sure there aren't any that would explain the issue? Used a debugger to see why it's not doing what it's supposed to? – Sami Kuhmonen Jun 18 '15 at 09:11
  • Another approach is to store these info in a database. Each time the file is created, you add a row with its CreationDate. You can simply then find all files older than N days –  Jun 18 '15 at 09:16
  • @SamiKuhmonen - Exceptions is a very weak point for me, whats the best way to go about it? – South Wilts Jun 18 '15 at 09:18
  • @Kilanny there is a database, which holds the path to the file and date to display the file (these are done on a daily basis, so only show for one day). We then want the files deleted from the directory if they're more than 10 days old as it's just going to be cluttered otherwise – South Wilts Jun 18 '15 at 09:18
  • @SouthWilts Can't you keep your database always up-to-date by updating rows each time you modify/create a file? Just depend on your data, do not use Windows file system anymore. –  Jun 18 '15 at 09:20
  • So what is the issue ? Are you getting any error or exception ? – Mairaj Ahmad Jun 18 '15 at 09:20
  • @Kilanny, the database is always updated on a daily basis, Monday to Friday, but when it updates the database, we want the file that would then be from 10 days ago removed from the directory to prevent clutter. – South Wilts Jun 18 '15 at 09:21
  • @MairajAhmad it seems to do nothing. The database updates fine and inserts the new record, but it then doesn't delete the files which are older than 10 days from the directory – South Wilts Jun 18 '15 at 09:22
  • Are you getting files in `FSI` ? – Mairaj Ahmad Jun 18 '15 at 09:23
  • @MairajAhmad through debugging? Annoyingly, Moxiemanager doesn't seem to work when debugging – South Wilts Jun 18 '15 at 09:32
  • @SouthWilts I have copied the same code and it is deleting files ? Can u make sure that path is correct ? Is `Files` folder on root and `Bulletins` folder inside the `Files` folder? – Mairaj Ahmad Jun 18 '15 at 09:41
  • You are sure the files are 10 days old right? In Windows explorer show the CreatedDate column and confirm because I've run the code and deletion works as expected for me. – Jeremy Thompson Jun 18 '15 at 09:46
  • Ah, that's why! @JeremyThompson, I was looking at the Modified Date. Do you know the ModifiedDate rather then CreationDate? – South Wilts Jun 18 '15 at 09:54
  • Change your if condition like this `if (fInfo.LastWriteTime < dt)` – Mairaj Ahmad Jun 18 '15 at 09:57

3 Answers3

3

You need to get LastModifiedDate of file which you can get by property LastWriteTime of FileSystemInfo class.

Change your if condition like this

if (fInfo.LastWriteTime < dt)
{
 //your code
}
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40
0

try to write query for this and apply it in the code.

var cutoff = DateTime.Now.AddDays(-10);
    var path = new DirectoryInfo(sourcePath);
    var query = path.GetFiles(filename, SearchOption.TopDirectoryOnly)
                    .Where(fi => fi.CreationTime < cutoff);

try the query, this may be easy and helpful to you.

Dinav Ahire
  • 581
  • 1
  • 10
  • 30
0

Code is as follows:

[HttpPost]
public ActionResult CreateMain(BulletinsViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        BulletinsContext.tblBulletins.Add(new tblBulletin
        {
            ID = viewModel.BulletinID,
            BulletinDisplayDate = viewModel.BulletinDisplayDate,
            BulletinFilename = viewModel.MainBulletinName
        });

        //Delete files older than X amount of days
        DirectoryInfo DI = new DirectoryInfo("D:/Inetpub/WWWroot/intranet/Dashboard/Dashboard/Files/Bulletins");
        FileSystemInfo[] FSI = DI.GetFiles();
        foreach (FileSystemInfo fInfo in FSI)
        {
            if (fInfo.Extension == ".pdf")
            {
                DateTime dt = DateTime.Now.AddDays(-10);
                if (fInfo.LastWriteTime < dt)
                    try
                    {
                        fInfo.Delete();
                    }
                    catch { }
            }
        }

        BulletinsContext.SaveChanges();
        return RedirectToAction("MainBulletins");
    }
South Wilts
  • 121
  • 1
  • 14