Friday, October 22, 2010

Delete Files created one week before

  public void DeleteOldFiles()
        {
            DirectoryInfo di = new DirectoryInfo(MapPath("Temp//"));
            FileInfo[] rgFiles = di.GetFiles("*.xml");
            foreach (FileInfo fi in rgFiles)
            {
                string filename = fi.Name;
                int index = filename.IndexOf("@");

                string date = filename.Substring(0, index);
                date = date.Replace("_", "/");
                date = date.Replace("-", ":");
                date = date.Replace("$", " ");
                DateTime fromdate;
                DateTime todate;
                string strFromDate = date;
                string strToDate = DateTime.Now.ToString();
                if (DateTime.TryParse(strFromDate, out fromdate) && DateTime.TryParse(strToDate, out todate))
                {
                    TimeSpan TS = todate - fromdate;
                    int daysDiff = TS.Days;
                    if (daysDiff > 7)
                    {
                        fi.Delete();
                    }
                }
            }


        }

Here all files are stored with datetime attached to them before the filename in Temp folder.
We are trying to remove the datetime part from the respective filename so that we can delete the file if it is older than 1 week.