Page 1 of 1

Delete reports in Project Files Folder

Posted: Thu Jan 19, 2017 4:40 pm
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.

Re: Delete reports in Project Files Folder

Posted: Mon Jan 23, 2017 12:22 pm
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