0

I have a folder named PCLtoMove. I have applied a filewatcherSystem in this folder to move files from this folder to another folder. first time when I start windows service It works fine but from next time it gives exception-

The process cannot access the file 'C:\PCLtoMove\fileName.pcl' because it is being used by another process.

my code to move file is -

 private void SavionFileWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        try
        {
            string sourcePath = e.FullPath;
            string destination = ConfigurationManager.AppSettings["destination"] + e.Name;
            File.Move(sourcePath, destination);

        }
        catch (Exception ex)
        {
            this.EventLog.WriteEntry(ex.Message, EventLogEntryType.Information);
        }

    }

please tell me whats wrong I am doing.

Vivek Mishra
  • 1,772
  • 1
  • 17
  • 37
  • 1
    One of the things you're doing wrong is not showing your research, nor that you have debugger. Read [ask]. My best guess: the event is raised as soon as the file is created, but it's still being written to. – CodeCaster Dec 15 '15 at 12:04
  • @codeCaster when I debug this windows service by attaching the process, it runs fine but when I deattach debuger, and file comes to the folder, it gives above mentioned exception in event logger. – Vivek Mishra Dec 15 '15 at 12:09
  • 2
    Yeah so the debugging (or you waiting at a breakpoint) slows it down enough that the file gets written and closed. See [Wait until file is unlocked in .NET](http://stackoverflow.com/questions/50744/wait-until-file-is-unlocked-in-net) for a naive approach. – CodeCaster Dec 15 '15 at 12:09

1 Answers1

0

I got the solution by adding following code to the above code. Its confirms that the file is completely moved or created.

 FileStream fs = new FileStream(sourcePath, FileMode.Open, FileAccess.ReadWrite);
                    fs.ReadByte();
                    fs.Seek(0, SeekOrigin.Begin);
                    fs.Dispose();
                    File.Move(sourcePath,destination);
                       break;
Vivek Mishra
  • 1,772
  • 1
  • 17
  • 37