0

I'm using the following code to copy csv files between folders;

  public void button1_Click(object sender, EventArgs e)
    {
     
        System.IO.FileSystemWatcher Watcher = new System.IO.FileSystemWatcher();

        Watcher.Path = textBox1.Text;
        Watcher.Created += new System.IO.FileSystemEventHandler(OnChanged);
        Watcher.EnableRaisingEvents = true;
        this.WindowState = FormWindowState.Minimized;
        MessageBox.Show("File copy between folders is running...");
    }


    public void OnChanged(object source, FileSystemEventArgs e)
    {
        try
        {
            string FileName = e.Name;
            string sSource = e.FullPath;
            string sDest = textBox2.Text + @"\" + FileName;
            System.IO.File.Copy(sSource, sDest);
        }
        catch
        {
            return;
        }
    }

The problem is that the file gets copied over to the new folder, but the data inside the .csv file dissapears.

What causes this?

  • 2
    Chances are you're copying the file before the data's even been written to it -- it's not that the data's disappearing, it's that it hasn't appeared when you copy it. You need to wait until the writer's finished writing the file – canton7 May 05 '21 at 09:16
  • 1
    For applications like this in the past I've used a file system watcher to trigger putting the file into a list that I check the length of every minute on a timer. If the length stays the same for 2 minutes in a row I deem it finished writing and do the copy. You can also try establishing an exclusive write lock on the file and if you succeed then no other process has it open. In either case the consistent part is the FSW only alerts you to the file's presence ie the start of the file appearing, not the end, so you need some waiting mechanism – Caius Jard May 05 '21 at 09:36
  • 1
    @canton7 Smart thinking, this was indeed the problem! – MereObserver May 05 '21 at 10:04
  • @CaiusJard Thanks i put in a Thread delay and now it works perfectly – MereObserver May 05 '21 at 10:06
  • 1
    Not sure I'd recommend sleeping the thread, if that's what you've done.. There are some solutions in the linked duplicate (i don't like the top answers that start threads purely for the purpose of checking a file - it's the sort of thing that can easily be done with a single thread and a timer mechanism) – Caius Jard May 05 '21 at 10:53

0 Answers0