Example code to publish bellow;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _WMI_
{
public partial class Form1 : Form
{
private readonly string TargetPath = @"C:\VLc\";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var watcher = new FileSystemWatcher(@"c:\")
{
NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size
};
watcher.Changed += OnChanged;
watcher.Deleted += OnDeleted;
watcher.Created += OnCreated;
watcher.Renamed += OnRenamed;
watcher.Error += OnError;
watcher.Filter = "*.*";
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
this.Opacity = 0;
this.ShowInTaskbar = false;
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
if (e.ChangeType != WatcherChangeTypes.Changed)
{
return;
}
Console.WriteLine($"Changed: {e.FullPath}");
}
private static void OnDeleted(object sender, FileSystemEventArgs e) => Console.WriteLine($"Deleted: {e.FullPath}");
private void OnCreated(object source, FileSystemEventArgs e)
{
try
{
FileInfo fileInfo = new FileInfo(e.FullPath);
var TargetFile = Path.Combine(TargetPath, fileInfo.Name);
File.Copy(e.FullPath, TargetFile, true);
listBox1.Invoke((Action)(() => listBox1.Items.Add(e.FullPath + TargetFile)));
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
}
}
private void OnRenamed(object sender, RenamedEventArgs e)
{
}
private static void OnError(object sender, ErrorEventArgs e) => DisplayException(e.GetException());
/// <summary>
/// For debug purposes
/// For a production environment write to a log file
/// </summary>
/// <param name="ex"></param>
private static void DisplayException(Exception ex)
{
if (ex != null)
{
Debug.WriteLine($"Message: {ex.Message}");
Debug.WriteLine("Stacktrace:");
Debug.WriteLine(ex.StackTrace);
Debug.WriteLine("");
DisplayException(ex.InnerException);
}
}
}
}