10 Haziran 2021 Perşembe

C# ile pop-up bildirim veren FileSystemWatcher uygulaması


Ağ üzerinde herhangi bir klasörde yeni bir dosya oluşturulduğunda, dosya değiştirildiğinde ya da silindiğinde pop-up bildirim alarak, bu bildirimleri ayrıca loglamak için C# basit bir uygulama geliştirmek istersek şayet, FileSystemWatcher kullanmak işimizi oldukça kolaylaştıracaktır.



Programın açılışında belirlediğimiz Path üzerindeki dosya değişikliklerini, dilersek alt klasörleriyle birlikte opsiyonel olarak inceleyebilmek için yukarıdaki gibi bir Form oluşturalım. Pop-up bildirimler için de Tulpep.NotificationWindow paketini projemize ekleyelim.


Kodumuz aşağıdaki gibi başlayacak.
using System;
using System.IO;
using System.Windows.Forms;
using System.Reflection;
using Tulpep.NotificationWindow;

namespace FileNotifierV2
{
    public partial class Form1 : Form
    {
        private string exePath = string.Empty;

        public Form1()
        {
            InitializeComponent();
        }

Dosya değişikliklerini pop-up bildirimlerle göstermenin yanısıra, uygulamamızın çalıştığı ana dizinde log.txt adlı bir dosyaya raporlayacağız. Bunun için LogWrite fonksiyonumuzu yazalım.

        public void LogWrite(string logMessage)
        {
            exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            try
            {
                using (StreamWriter logFile = File.AppendText(exePath + "\\" + "log.txt"))
                {
                    logFile.Write("\r\n{0}", logMessage);
                }
            }
            catch (Exception ex)
            {
            }
        }   

FileSystemWatcher eventlarını da kodlayarak programımızın esas fonksiyonlarını tanımlayalım.

  private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                string time = DateTime.Now.ToString("h:mm:ss");
                string alert = string.Format("File created {0} {1} - {2}", e.FullPath, e.Name, time);
                listBox1.BeginUpdate();
                listBox1.Items.Add(alert);
                listBox1.EndUpdate();
                LogWrite(alert);
                popupNotifier1.TitleText = "File Created!";
                popupNotifier1.ContentText = alert;
                popupNotifier1.Popup();
            }
        }

        private void fileSystemWatcher1_Deleted(object sender, FileSystemEventArgs e)
        {
            if (checkBox2.Checked == true)
            {
                string time = DateTime.Now.ToString("h:mm:ss");
                string alert = string.Format("File deleted {0} {1} - {2}", e.FullPath, e.Name, time);
                listBox1.BeginUpdate();
                listBox1.Items.Add(alert);
                listBox1.EndUpdate();
                LogWrite(alert);
                popupNotifier1.TitleText = "File Deleted!";
                popupNotifier1.ContentText = alert;
                popupNotifier1.Popup();
            }
        }

        private void fileSystemWatcher1_Renamed(object sender, FileSystemEventArgs e)
        {
            if (checkBox3.Checked == true)
            {
                string time = DateTime.Now.ToString("h:mm:ss");
                string alert = string.Format("File renamed {0} {1} - {2}", e.FullPath, e.Name, time);
                listBox1.BeginUpdate();
                listBox1.Items.Add(alert);
                listBox1.EndUpdate();
                LogWrite(alert);
                popupNotifier1.TitleText = "File Renamed!";
                popupNotifier1.ContentText = alert;
                popupNotifier1.Popup();
            }
        }

        private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
        {
            if (checkBox4.Checked == true)
            {
                string time = DateTime.Now.ToString("h:mm:ss");
                string alert = string.Format("File changed {0} {1} - {2}", e.FullPath, e.Name, time);
                listBox1.BeginUpdate();
                listBox1.Items.Add(alert);
                listBox1.EndUpdate();
                LogWrite(alert);
                popupNotifier1.TitleText = "File Changed!";
                popupNotifier1.ContentText = alert;
                popupNotifier1.Popup();
            }
        }

Path seçimi fonksiyonumuzu da kodlayacak ve açılışta path seçimi fonksiyonunu Form_Load ile çağıracağız. Bununla birlikte istediğimiz zaman Path'i değiştirebilmek için bir de command button eklemiştik, bunu da PathSelect fonksiyonumuza bağlayacağız.

        private void Form1_Load_1(object sender, EventArgs e)
        {
            PathSelect();
        }

        private void checkBox5_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox5.Checked == true)
            {
                fileSystemWatcher1.IncludeSubdirectories = true;
            }
            else
            {
                fileSystemWatcher1.IncludeSubdirectories = false;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            PathSelect();
        }

        private void PathSelect()
        {
            using (var fbd = new FolderBrowserDialog())
            {
                DialogResult result = fbd.ShowDialog();

                if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
                {
                    textBox1.Text = fbd.SelectedPath;
                    fileSystemWatcher1.Path = fbd.SelectedPath;
                }
            }
        }

Kodların güncel halini ve derlenmiş halini Github sayfamdan indirebilirsiniz.

Hiç yorum yok:

Yorum Gönder