Delete reports in Project Files Folder

A forum devoted to the discussion of all topics having to do with scripting and other advanced programming using iX Developer.
Post Reply
ianrobo75
Posts: 12
Joined: Mon Sep 22, 2014 6:15 pm

Delete reports in Project Files Folder

Post by ianrobo75 »

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.

AMitchneck
Posts: 137
Joined: Mon Jun 11, 2012 2:10 pm

Re: Delete reports in Project Files Folder

Post by AMitchneck »

Hi ianrobo75,

I had a similar problem and created the following solution:

Code: Select all

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: Select all

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/librar ... .110).aspx
Adam M.
Controls Engineer
FlexEnergy

Post Reply