I have a directory with around 15-30 thousand files. I need to just pull the oldest one. In other words the one that was created first. Is there a quick way to do this using C#, other than loading them into a collection then sorting?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
If you control the directory (that is, if your programs are responsible for creating and maintaining all files in that directory), then you should consider tracking the metadata about each file separately; perhaps in a database.
In fact, the FileStream column type in SQL Server 2008 can help with this. You can create a table that contains columns for filename, create date, modify date, and a FileStream column for the content. You can find things like the oldest file by using indexes on the metadata columns. You can find the content by using the FileStream column.
You can't do it without sorting but what you can do is make it fast.
Sorting by
CreationTime
can be slow because first accessing this property for each file involves interrogation of the file system.Use A Faster Directory Enumerator that preserves more information about files while enumerating and allows to do sorting faster.
Code to compare performance:
For me it gives this:
You will have to load the FileInfo objects into a collection & sort, but it's a one-liner:
Ok, two lines because it's a long statement.
Oddly enough, this worked perfectly on a directory of mine with 3000+ jpg files:
Edit: Removed the sort and made it a function.
The short answer is no. Windows file systems don't index files by date so there is no native way to do this, let alone a .net way without enumerating all of them.