File in use error when I copy and move a file

Stefano Mora 1 Reputation point
2023-03-01T10:05:10.53+00:00

Hi all,

I'm writing a WinForm C# program that watches a folder by a FileSystemWatcher.

When a file (4kb) arrives in that folder I copy it in two other foldes: so far I achieve that by File.Copy() then File.Move() calls.

On the Move() call I always have an IoException: File in use from other process.

The operation is done on a control.Invoke() function, here I added a secondary thread and in plus I separated Copy and Move calls with a Sleep(1000).

Nothing to do, always IoException.

The Copy operation is synchronous, is it?

By some Console.Write() calls I see that the filesystemWatcher funtion is done when the Move function is invoked ..

How can I solve?

Which process is using the file?

Thanks, regards

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,386 Reputation points
    2023-03-01T11:38:10.41+00:00

    To rule out Copy method being the issue try the following.

    public static async Task CopyFileAsync(string sourceFile, string endDirectory)
    {
        await using FileStream sourceStream = File.Open(sourceFile, FileMode.Open);
        await using FileStream destinationStream = File.Create(
            Path.Combine(endDirectory, Path.GetFileName(sourceFile)));
        await sourceStream.CopyToAsync(destinationStream);
    }
    

    Source

    0 comments No comments

  2. Stefano Mora 1 Reputation point
    2023-03-01T13:15:25.1633333+00:00

    I found the problem.

    The file was an image: the was caused by the missing Dispose() of the image after the Image.LoadFromFile().

    Thanks anyway.

    0 comments No comments