I'm using the file watcher class in C# and anytime a file is created/modified I want to write that change to a log file. Should I have the StreamWriter open and write to the file upon each notification? Or should the StreamWriter be a member variable that is left open until the program is closed? The program does nothing else but watch a specific subdirectory and log changes.
using System;
using System.IO;
using System.Security.Permissions;
public class Watcher
{
private static string path;
public static void Main()
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private static void Run()
{
//gets input from user for assigns it to path
// Create a new FileSystemWatcher and set its properties.
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
using (StreamWriter outputFile = File.AppendText(path))
{//write to file with time stamp indicating file watch
//start time
}
watcher.Path = path;
// 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.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Renamed += 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){
using (StreamWriter outputFile = File.AppendText(path))
{//write to file with time stamp indicating what changed
}
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
}
private static void OnRenamed(object source, RenamedEventArgs e){
using (StreamWriter outputFile = File.AppendText(path))
{//write to file with time stamp indicating what renamed
}
// Specify what is done when a file is renamed.
Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");
}
}