In this post we are going to learn how to keep close eyes on each folder or file in c#.
Valid points:
Valid points:
- We are using System.IO namespace.
- We are using FileSystemWatcher.
- Tracking Changed event
- Tracking Created event
- Tracking Deleted event
- Tracking Renamed event
- Including all sub folders and files
- Can apply filter for particular file extension.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Permissions;
using System.IO;
namespace FolderWatcher
{
class Program
{
public static void Main()
{
try
{
Run();
}
catch(Exception ex) {
Console.Write(ex.Message);
}
Console.Read();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
string[] args = System.Environment.GetCommandLineArgs();
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "E:\\";
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files. Use of multiple filters such as *.txt|*.doc is not supported.
//watcher.Filter = "*.txt";
//including all sub folders and files
watcher.IncludeSubdirectories = true;
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine(FileFolderType(e.FullPath) + " " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Console.WriteLine(FileFolderType(e.FullPath) + " " + "{0} renamed to {1}", e.OldFullPath, e.FullPath);
}
public static string FileFolderType(string filefolderpath)
{
try
{
FileAttributes attr = File.GetAttributes(filefolderpath);
//detect whether its a directory or file
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
return "Folder";
else
return "File";
}
catch {
return "file";
}
}
}
}