I Have created a program to watch a notepad file using filewatcher.. whenever the text in the file changes.. I made a .exe program to run... the .exe program also runs properly.. But it runs twice... I searched Stackoverflow and also other websites.. but I couldnt understand where I have went wrong.. Frnds Plz help me in clearing my error.. I know this question has been asked many times.. But since im new to this c# I couldnt understand.. Plz help me frnds..
public Form1()
{
InitializeComponent();
}
private void filewatcher()
{
path = txtBoxPath.Text;
FileSystemWatcher fileSystemWatcher1 = new FileSystemWatcher();
fileSystemWatcher1.Path = path;
fileSystemWatcher1.Filter = "*.txt";
fileSystemWatcher1.NotifyFilter = NotifyFilters.LastWrite;
fileSystemWatcher1.Changed += new FileSystemEventHandler(OnChanged);
fileSystemWatcher1.EnableRaisingEvents = true;
}
private void tbtextcopy()
{
Clipboard.SetText(File.ReadAllText(path));
this.textBox1.Text = Clipboard.GetText().ToString();
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
try
{
ProcessStartInfo PSI = new ProcessStartInfo(@"C:\Program Files\Ranjhasoft\Icon Changer\Icon changer.exe");
Process P = Process.Start(PSI);
P.WaitForExit();
P.Close();
}
finally
{
fileSystemWatcher1.EnableRaisingEvents = false;
}
}
private void BrowserBtn_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.SelectedPath = this.txtBoxPath.Text;
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.OK)
{
if (!string.IsNullOrEmpty(dlg.SelectedPath))
{
this.txtBoxPath.Text = dlg.SelectedPath;
}
}
if (string.IsNullOrEmpty(this.txtBoxPath.Text))
{
this.txtBoxPath.Text = appDataFolder;
}
if (!Directory.Exists(path))
{
MessageBox.Show("Specified folder does not exist");
}
}
private void txtBoxPath_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(this.txtBoxPath.Text))
{
this.filewatcher();
}
}
}
}
You have the code
fileSystemWatcher1.Changed += new FileSystemEventHandler(OnChanged);
you can be repeatedly adding the same event handler to the event.. so yes, it could do it 20 times..
You only need set it to run the code once, so only add it once. If you stop firing events, the event handler doesnt wipe. So set the eventhandler once, and not each time in your filewatcher method which will repeatedly add the same handler and produce multiple responses.
So change your code here:
public Form1()
{
InitializeComponent();
fileSystemWatcher1.Changed += new FileSystemEventHandler(OnChanged);
}
and remove it from the filewatcher method. Now it will run once, when the raiseevents is set true, and not at all when it isnt.