删除它们比今天的日期较旧的文件 [英] Delete files which are older than today's date
问题描述
我在yyyyMMdd_hhmmss_abc.txt在特定位置的格式的某些文件。
使用下面的code,我能够获得与该文件夹中的_abc.txt的所有文件。
fileArray = Directory.GetFiles(@C://文档,*的abc.txt);
的for(int i = 0; I< fileArray.Length;我++)
{
fileArray [I] = Path.GetFileNameWithoutExtension(fileArray [I]);
Console.WriteLine(fileArray [I]);
}
但现在我想读的文件名,分割,然后转换成日期时间对象,这样我可以检查的条件(在今天的日期以上)并删除它们。
为例如:20160426_045823_abc.txt
块引用>我想将它分成2016年,04,26,然后用转换成日期时间对象
日期时间D1 =新日期时间(2016,04,26)
然后再进行其他操作。是否有任何其他方式来解决这个问题?
在此先感谢
解决方案文件名已经在基于日期可排序格式。相反,分析文件名的位转换成DateTime对象,为什么不创建一个基于今天的日期文件名和过滤文件名数组下降到只有那些字符串比较少比你能正确安装当今最新的文件名?这可能不是在每个文件名执行日期解析速度快了不少,对于文件的大名单。
例如:
VAR PATH =C:\\\\无所谓;
VAR后缀=_abc.txt;
VAR todaysFilename = DateTime.Now.ToString(YYYYMMDD_HHMMSS)+后缀;
VAR filesToDelete = Directory.EnumerateFiles(路径,*+后缀)
。选择(Path.GetFileName)
。凡(文件名=>的String.Compare(文件名,todaysFilename,StringComparison.Ordinal)℃下)
.ToArray();的foreach(在filesToDelete var文件)
{
File.Delete(Path.Combine(路径,文件));
}I have some files in the format of "yyyyMMdd_hhmmss_abc.txt" in a particular location. using the below code i am able to get all the files with "_abc.txt" in that folder.
fileArray = Directory.GetFiles(@"C://Documents", "*abc.txt"); for (int i = 0; i < fileArray.Length; i++) { fileArray[i] = Path.GetFileNameWithoutExtension(fileArray[i]); Console.WriteLine(fileArray[i]); }
But now I'm thinking of reading the file name, split it and then convert into date time object so that i can check for the condition(older than today's date) and delete them.
for eg: 20160426_045823_abc.txt
I want to split it into 2016, 04 , 26 and then convert into date time object using
Datetime d1 = new Datetime(2016,04,26)
and then do other operations.Is there any other way to solve this problem?
Thanks in advance
解决方案The filename is already in a sortable format based on the date. Instead of parsing bits of the filename into a DateTime object, why not create a filename based on today's date and filter your array of filenames down to only those that are string-comparison-less than your today's-date filename? It's probably quite a bit faster than doing date parsing on each filename, for large lists of files.
For example:
var path = "c:\\whatever"; var suffix = "_abc.txt"; var todaysFilename = DateTime.Now.ToString("yyyyMMdd_hhmmss") + suffix; var filesToDelete = Directory.EnumerateFiles(path, "*" + suffix) .Select(Path.GetFileName) .Where(fileName => string.Compare(fileName, todaysFilename, StringComparison.Ordinal) < 0) .ToArray(); foreach (var file in filesToDelete) { File.Delete(Path.Combine(path, file)); }
这篇关于删除它们比今天的日期较旧的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!