0

I am getting this error when a new file is added to a folder:

The process cannot access the file 'C:\Folder\New Text Document.txt' because it is being used by another process.

I am trying to find a solutions here on SO but none has worked for me. My code at the moment now is:

private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
{
    fileWatcher1.Items.Add(string.Format("File Created:  {0} File Name:  {1}", e.FullPath, e.Name)).ForeColor = Color.Green;
}

EDIT

The error gets thrown here:

using (var fileStream = File.OpenRead(e.FullPath)) --> HERE
        {
            BinaryReader reader = new BinaryReader(fileStream);
            file = reader.ReadBytes((int)fileStream.Length);
            fileStream.Close();
        }

So every time I add a new file I get the above error?

Thanks

  • See this previous answer may help you https://stackoverflow.com/questions/21739242/filestream-and-a-filesystemwatcher-in-c-weird-issue-process-cannot-access-the] – Ammar Mousa Feb 05 '20 at 06:04
  • Hi, thanks. I just tried that it still doesn't seem to work. I can add the first file, but when I add another one it crashes. –  Feb 05 '20 at 06:39
  • Hi I have updated my Question with some more code –  Feb 05 '20 at 06:56

1 Answers1

0

The file may be opened in your system. Make sure its closed/deleted.

https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher.created?view=netframework-4.8