The following C# code will remove .xel files that are older than one month from the specified folder. I'm guessing you only want to look at the date, not time, that the file was created thus CreationTime.Date
is compared to DateTime.Today
, and any files older than one month are deleted. A reference to the System.IO
namespace will be necessary. If the extended event is currently active it will be using the file and the file will not be able to be deleted. You can either handle this using try...catch
blocks in your code or run a command to stop the event before deleting the files then turn the event back on afterwards. Taking the approach of starting and stopping each event will require knowing the name of the specific event to use as done below. If using this option, you can send these as SQL Commands from C# code or as another step in a SQL Agent job. The T-SQL example stops an extended event, and it can be re-enabled by changing the STATE
to START
instead.
Example Stop Event Statement:
ALTER EVENT SESSION YourExtendedEvent ON SERVER
STATE = STOP
Delete old Extended Event Files:
string directory = @"C:\YourFilePath\";
DirectoryInfo di = new DirectoryInfo(directory);
foreach (FileInfo fi in di.EnumerateFiles())
{
if (fi.Extension == ".xel" && fi.CreationTime.Date < DateTime.Today.AddMonths(-1))
{
fi.Delete();
}
}