when we a console application to clean some historical files from the folder, we will add an app settings section in the app.config file in project, which is run under .net framework. however it is much flexible to run with .Net Core.
i will show you my first sample DotNet Core Console App to handle this task.
1. Launch Visual Studio and create a new project by selecting the Console App (.Net Core)
2. Open the management studio and select the project, then right click to show the menu, select Add to get the New Item from slide out menu. to add JSon Config file
3. Open the JSon file and filll with the following information
{
"PrintFolder": "the folder you want to delete files",
"FileExtension": ".pdf",
"DaysToMaintain": "15"
}
4. Load the config information into the program using the snippet of code below
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
var fileExtension = config["FileExtension"];
var daysToKeepFiles = -1* Convert.ToInt32(config["DaysToMaintain"]);
var ltlPrintFolder = config["LTLPrintFolder"];
Console.WriteLine($"ltl print folder path : { ltlPrintFolder}");
5. Use the LINQ to manipulate the logic on what kind of file and Periods based on the file creation time.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(ltlPrintFolder); IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
IEnumerable<System.IO.FileInfo> fileQuery =
from file in fileList
where file.Extension == fileExtension && file.CreationTime < DateTime.Now.AddMonths(daysToKeepFiles)
orderby file.Name
select file;
6. loop through the result from the query
foreach (System.IO.FileInfo fi in fileQuery)
{
Console.WriteLine(fi.FullName);
fi.Delete();
}
Now you can delete file with Dot Net Core App
No comments:
Post a Comment