Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out when file is added to folder

Tags:

c#

file

directory

I would like to know if it is possible to find out when a file is added to a folder in C#. I know you can see the time of creation and many other things in the FileInfo, but nok when it was added.

like image 663
Mikkel Avatar asked Feb 07 '12 14:02

Mikkel


People also ask

How can I tell when a file was added?

Right-click the file and select Properties. In the Properties window, the Created date, Modified date, and Accessed date is displayed, similar to the example below.

How do I find recently added files on my computer?

To view the Downloads folder, open File Explorer, then locate and select Downloads (below Favorites on the left side of the window). A list of your recently downloaded files will appear. Default folders: If you don't specify a location when saving a file, Windows will place certain types of files into default folders.

How do I view folder logs?

Locate the parent directory or folder in which you want to track creation and deletion of files/sub folders. Right click on it and go to Properties. Under the Security tab click Advanced. In Advanced Security Settings, go to the Auditing tab and click Add to add a new auditing entry.


2 Answers

You can use the System.IO.FileSystemWatcher. It provides methods to do exactly what you want to do:

FileSystemWatcher watcher = new FileSystemWatcher()
{
    Path = stringWithYourPath,
    Filter = "*.txt"
};
// Add event handlers for all events you want to handle
watcher.Created += new FileSystemEventHandler(OnChanged);
// Activate the watcher
watcher.EnableRaisingEvents = true

Where OnChanged is an event handler:

private static void OnChanged(object source, FileSystemEventArgs e)
{
    Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
}
like image 78
PVitt Avatar answered Oct 16 '22 13:10

PVitt


FileSystemWatcher is a very powerful component, which allows us to connect to the directories and watch for specific changes within them, such as creation of new files, addition of subdirectories and renaming of files or subdirectories. This makes it possible to easily detect when certain files or directories are created, modified or deleted. It is one of the members of System.IO namespace.

Full Tutorial Here

It has events and theyare

  • Created - raised whenever a directory or file is created.
  • Deleted - raised whenever a directory or file is deleted.
  • Renamed - raised whenever the name of a directory or file is changed.
  • Changed - raised whenever changes are made to the size, system attributes, last write time, last access time or NTFS security permissions of a directory or file.
like image 24
John Woo Avatar answered Oct 16 '22 12:10

John Woo