@Chocolade , Welcome to Microsoft Q&A, I suggest that you could use Dictionary to store the path and file size.
I make a code example and you could refer to it.
FileSystemWatcher watcher = new FileSystemWatcher("E:\\Test");
List<string> filelist = new List<string>();
Dictionary<string, long> dic = new Dictionary<string, long>();
private void Form1_Load(object sender, EventArgs e)
{
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
watcher.Changed += Watcher_Changed;
watcher.Created += Watcher_Created;
watcher.Renamed += Watcher_Renamed;
watcher.Filter = "*.txt";
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
watcher.SynchronizingObject = this;
filelist = Directory.GetFiles("E:\\Test", "*.txt").ToList();
foreach (var item in filelist)
{
FileInfo info = new FileInfo(item);
dic.Add(item, info.Length);
}
}
private void Watcher_Renamed(object sender, RenamedEventArgs e)
{
FileInfo info = new FileInfo(e.FullPath);
if(dic.ContainsKey(e.FullPath))
{
dic[e.FullPath] = info.Length;
}
else
{
dic.Add(e.FullPath, info.Length);
}
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
string time = DateTime.Now.ToString("h:mm:ss tt");
if (!richTextBox1.Text.Contains(e.FullPath))
{
richTextBox1.AppendText($"File Name : {e.Name} ");
richTextBox1.AppendText($"Created At : {time}");
filelist.Add(e.FullPath);
FileInfo info = new FileInfo(e.FullPath);
if (dic.ContainsKey(e.FullPath))
{
dic[e.FullPath] = info.Length;
}
else
{
dic.Add(e.FullPath, info.Length);
}
}
}
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
if (e.ChangeType != WatcherChangeTypes.Changed)
{
return;
}
else
{
var info = new FileInfo(e.FullPath);
var newSize = info.Length;
var oldsize = dic[e.FullPath];
string FileN1 = "File Name : ";
string FileN2 = info.Name;
string FileN3 = " Size Changed : From ";
string FileN4 = oldsize.ToString();
string FileN5 = "To";
string FileN6 = newSize.ToString();
if (newSize!=oldsize)
{
richTextBox1.AppendText(FileN1);
richTextBox1.AppendText(FileN2);
richTextBox1.AppendText(FileN3);
richTextBox1.AppendText(FileN4);
richTextBox1.AppendText(FileN5);
richTextBox1.AppendText(FileN6);
richTextBox1.AppendText("\n");
}
if (dic.ContainsKey(e.FullPath))
{
dic[e.FullPath] = info.Length;
}
else
{
dic.Add(e.FullPath, info.Length);
}
}
}
Tested Result:
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.