0

I have a root directory and inside that further directories are there. These directories contains various Html and ncx files. I have to get the name of the file that has been last modified. I am using this code

    string filePath = @"~\FolderName\";  
string completeFilePath = Server.MapPath(filePath);  
var directory = new DirectoryInfo(completeFilePath);  
var fileName = (from f in directory.GetFiles()  
orderby f.LastWriteTime descending  
select f).First();  
lblDisplayFileName.Text=fileName.ToString();  

But it is only searching files that are placed only in root directory. It is not searching files that are present further in directories of root directory. I don't know how to get last modified filename of the files that are present further in nested directories. I have to display the name of file that has been last modified from all of the files irrespective of present in any directory.

user
  • 128
  • 2
  • 12

2 Answers2

0

Have a look at the documentation of DirectoryInfo.GetFiles:

MSDN:

Returns a file list from the current directory.

You have to use the overload that takes a SearchOption:

directory.GetFiles("*.*", SearchOption.AllDirectories) 
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • var dir = Directory.GetDirectories(path); for (int i = 0; i < dir.Count(); i++) { var dir1 = new DirectoryInfo(dir.ToString()); var fileName = (from f in dir1.GetFiles() orderby f.LastWriteTime descending select f).First(); MessageBox.Show(fileName.ToString()); } I have updated my code like this but still i am not getting my desired result. – user Jan 24 '14 at 09:25
  • can you please explain what changes should i do and where ? – user Jan 24 '14 at 09:26
  • @user: change your code `... from f in directory.GetFiles() ...` to `... from f in directory.GetFiles("*.*", SearchOption.AllDirectories) ...` – Tim Schmelter Jan 24 '14 at 09:41
0

Try the overload of GetFiles which takes 2 parameters

from f in directory.GetFiles(".", SearchOption.AllDirectories)

SearchOption specifies whether the search operation should include only the current directory or all subdirectories.