Deleting files in a directory after 7 days using Windows Services

Introduction: Here I am Taking one directory "DeleteData" which contains some files. Now I want delete these files after 7 days. So I am using windows service, this can be automatically deleting files after 7 days. Once you started the service when ever you shutdown your system your service still running. This service never stoped until your setup uninstalled. You must follow bellow Steps.

  1. First you Create Your windows  service

  2. Then write below code

  3. Here I am taking  "D:\DeleteData\" this is my directory where files are stored.
    Note:  Don't  forgot  after end of your directory name put ' \ ' in coding.
    string[] Files = Directory.GetFiles(@"D:\DeleteData\");

  4. Do you want MessageBox then add "System.windows.Forms" dll , then write your own messsage.

  5. Then go to MyComputers - right click - Manage - Services - Right Click on your service Name -  Properties - Logon Tab - Check on Allow interactive with Desktop.

  6. After Restart your service. Then you getting Messagebox.



Code:


using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Diagnostics;
using
System.Linq;
using
System.ServiceProcess;
using
System.Text;
using
System.IO;
using
System.Windows.Forms;
 

namespace
SEMIS_WindowsService
{

    public partial class Service1 : ServiceBase

    {

        System.Timers.Timer timer;

 

        public Service1()

        {

            InitializeComponent();

        }

       protected override void OnStart(string[] args)

        {

            Deletefile(); // This Method for Deleting files in DeleteData after 7 days.

        }

        protected void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

        {

            Deletefile()

        }

        public void Deletefile()

        {

            try

            {

                timer = new System.Timers.Timer();

                timer.Interval = (10000) * 6;

                timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);

                string[] Files = Directory.GetFiles(@"D:\DeleteData\");

                for (int i = 0; i < Files.Length; i++)

                {

                    //Here we will find wheter the file is 7 days old

                    if (DateTime.Now.Subtract(File.GetCreationTime(Files[i])).TotalDays > 7)

                    {

                        File.Delete(Files[i]);

                        MessageBox.Show("File Deleted Successfully");

                    }

                }

                timer.Enabled = true;

                timer.Start();

            }

            catch

            {

            }

        }

         protected
override void OnStop()
         {

           
         }

     }

}