问题描述
我在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]);
}
但现在我想读的文件名,分割,然后转换成日期时间对象,这样我可以检查的条件(在今天的日期以上)并删除它们。
I want to split it into 2016, 04 , 26 and then convert into date time object usingDatetime 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));
}
这篇关于删除它们比今天的日期较旧的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!