I want to traverse all the files in a directory recursively one by one using c#. also i need to check the modified date and created date of that specific file. I have used Directory.GetFiles(), but it gives me list of files in single instance. I want files should be traverse one by one like findfirstfile, findnextfile in c++
Asked
Active
Viewed 308 times
-4
-
[`Directory.EnumerateFiles()`](https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.enumeratefiles?view=net-5.0) – Matthew Watson Oct 14 '21 at 11:33
-
There is no built-in function for that, you were on the right path with `Directory.GetFiles()`. You need to access each file seperately and get their attributes, i.e. by using the [FileInfo class](https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=net-5.0) – Chrᴉz remembers Monica Oct 14 '21 at 11:35
-
1@Chr `Directory.GetFiles()` returns strings, but `DirectoryInfo.GetFiles()` returns FileInfos, on which you can inspect dates and stuff. – CodeCaster Oct 14 '21 at 11:52
1 Answers
0
I want files should be traverse one by one like findfirstfile, findnextfile in c++
Then you call those via P/Invoke, see https://www.pinvoke.net/default.aspx/kernel32.findfirstfile and https://www.pinvoke.net/default.aspx/kernel32.findnextfile.
But why? You're using managed code, use a friendlier API and the accompanying paradigms. Such as DirectoryInfo.GetFiles()
, which on Windows calls the same Win32 APIs.
If you insist on using the procedural paradigm, then you do this:
var files = new DirectoryInfo(path).GetFiles();
var enumerator = files.GetEnumerator();
while (enumerator.MoveNext())
{
var file = enumerator.Current;
// do something with file
}
Why though? The idiomatic way for that is a foreach
, which does the same but with some compiler magic that keeps the code readable:
foreach (var file in new DirectoryInfo(path).GetFiles())
{
// do something with file
}

CodeCaster
- 147,647
- 23
- 218
- 272
-
Note that I'm specifically not answering the recursive part of the question, as that's been answered in at least a dozen duplicates, I'm responding to the FindFirstFile() remarks. – CodeCaster Oct 14 '21 at 11:42