Home > Back-end >  How to get recent uploaded files from a Folder
How to get recent uploaded files from a Folder

Time:12-21

I have upload multiple files in a folder using c# but when I want to get all of the recently uploaded files ,I found all the files from that directory

  string Uplodefile = Request.PhysicalApplicationPath   "\\Content\\Uploads\\";
  string[] S1 = Directory.GetFiles(Uplodefile);

how can I get recent uploaded multiple file using string[].

CodePudding user response:

One solution is to sort the files in descending order by creation date. Now the newest file is in index 0, the next one is in index 1 and so on

 DirectoryInfo info = new DirectoryInfo(Request.PhysicalApplicationPath   "\\Content\\Uploads\\");
 FileInfo[] S1 = info.GetFiles().OrderByDescending(p => p.CreationTime).ToArray();
 string[] recentUploadedFiles= S1.Select(file => file.FullName).ToArray();

The second way is to say that I want get files that have been uploaded in the last 5 minutes (you can change the number 5).

 DirectoryInfo info = new DirectoryInfo(Request.PhysicalApplicationPath   "\\Content\\Uploads\\");
 FileInfo[] S1= info.GetFiles().Where(p => p.CreationTime > 
 DateTime.Now.AddMinutes(-5)).ToArray(); //DateTime.Now.AddMinutes(-5) ==>means subtract 5 minutes from the present time
 string[] recentUploadedFiles= S1.Select(file => file.FullName).ToArray();

CodePudding user response:

You are trying to get recent uploaded files by using Directory.GetFiles(). But as per the documentation this method:

Returns the names of files (including their paths) in the specified directory.

To get recently uploaded files from a directory, you have to enumerate files of that directory and specify a datetime by which condition you want to get your files.

On the below code snippet I use DateTime.Now.AddMinutes(-1) which will give the datetime of 1 minute earlier from your current time, and find all the files which CreationTime is greater than that time. And then take the FullPath of return files and store them into an array of string.

string[] S1 = new DirectoryInfo(Uplodefile).EnumerateFiles("*.*", SearchOption.AllDirectories)
.Where(file => file.CreationTime > DateTime.Now.AddMinutes(-1)).Select(file => file.FullName).ToArray(); 
  • Related