iX Talk
http://beijerinc.com/support/ix/forum/

Delete reports in Project Files Folder
http://beijerinc.com/support/ix/forum/viewtopic.php?f=6&t=2163
Page 1 of 1

Author:  ianrobo75 [ Thu Jan 19, 2017 4:40 pm ]
Post subject:  Delete reports in Project Files Folder

I'm looking for c# code to delete reports in the [local] Project Files Folder on the HMI. Can anyone help?

The project was designed for users to FTP the files off of the unit but when they fail to do so the unit fills up and falls over, so it would be good to delete reports if too much of the hard disk is used.

Author:  AMitchneck [ Mon Jan 23, 2017 12:22 pm ]
Post subject:  Re: Delete reports in Project Files Folder

Hi ianrobo75,

I had a similar problem and created the following solution:

Code:
using System.IO;

public int ExpungeFiles(string filePath, string filePattern, int keep)
{
   DirectoryInfo folder;
   FileInfo[] files;
   DateTime CreationTime;
   int i, j, nFiles;

   try { folder = new DirectoryInfo(filePath); }
   catch (ArgumentException) { return 0; }
   catch (PathTooLongException) { return 0; }
   if (folder == null) return 0;
   try { files = folder.GetFiles(filePattern); }
   catch (ArgumentException) { return 0; }
   catch (DirectoryNotFoundException) { return 0; }
   if (files == null) return 0;
   if ((keep < 0) || (files.Length <= keep))
      return files.Length;

   for (nFiles = files.Length; nFiles > keep; nFiles--)
   {
      // find file with oldest time stamp
      i = nFiles - 1;
      CreationTime = files[i].CreationTime;
      for (j = i - 1; j >= 0; j--)
      {
         if (CreationTime > files[j].CreationTime)
         {
            i = j;
            CreationTime = files[j].CreationTime;
         }
      }

      // delete file with oldest time stamp
      try { File.Delete(files[i].FullName); }
      catch (ArgumentException) { }
      catch (IOException) { }
      catch (NotSupportedException) { }
      catch (UnauthorizedAccessException) { }

      // remove file from list
      for (i++; i < nFiles; i++)
      {
         files[i - 1] = files[i];
      }
   }

   return keep;
}

To use this function you would write something like the following:
Code:
ExpungeFiles(@"\FlashDrive\Project\Project Files\", @"Record_*.txt", 10);
This would delete the oldest files in the project files directory that match the file pattern "Record_*.txt" so only 10 such files remain.
I call this function every time before I create a new file in the directory.

For more information on filePattern, see https://msdn.microsoft.com/en-us/library/8he88b63(v=vs.110).aspx

Page 1 of 1 All times are UTC - 7 hours [ DST ]
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/