Search code examples
c#filesystemwatcher

Why doesn't my FileSystemWatcher work?


I got a FileSystemWatcher, when i make a file in the first directory it should be going to the 2nd as well. So I want the file to be overwritten when it already exists in the 2nd directory. It wont work. I got this:

 private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
    {

            listBox1.Items.Add("File created> " + e.FullPath + " -Date:" + DateTime.Now);
            if (File.Exists(target+e.Name))
            {
                File.Delete(target+e.Name);
            }
            File.Copy(e.FullPath, Path.Combine(target, e.Name));
    }

and i got another problem: It is showing when a file is created but not when it's renamed, deleted, changed. Here is my code.:

private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
    {
        if (!pause)
        {
            listBox1.Items.Add("File changed> " + e.FullPath + " -Date:" + DateTime.Now);
        }

    }

    private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
    {

            listBox1.Items.Add("File created> " + e.FullPath + " -Date:" + DateTime.Now);
            if (File.Exists(target+e.Name))
            {
                File.Delete(target+e.Name);
            }
            File.Copy(e.FullPath, Path.Combine(target, e.Name));
    }

    private void fileSystemWatcher1_Deleted(object sender, System.IO.FileSystemEventArgs e)
    {
        if (!pause)
        {
            listBox1.Items.Add("File deleted> " + e.FullPath + " -Date:" + DateTime.Now);
            File.Delete(target+e.Name);
        }
    }

    private void fileSystemWatcher1_Renamed(object sender, System.IO.RenamedEventArgs e)
    {
        if (!pause)
        {
            listBox1.Items.Add("File renamed> " + e.FullPath + " -Date:" + DateTime.Now);
        }
    }
        private void Start_Click(object sender, EventArgs e)
    {
        fileSystemWatcher1.Path = source;
        if (!pause)
        {
            pause = true;
            Start.Text = "Pause";
            fileSystemWatcher1.EnableRaisingEvents = true;   
        }
        else
        {
            pause = false;
            Start.Text = "Start";
            fileSystemWatcher1.EnableRaisingEvents = false;

        }

    }

Solution

  • if(!pause){

    } is causing the problem you have to remove it.