Home > Software engineering >  C# .NET - Exception ("... is being used by another process.") when copying a file
C# .NET - Exception ("... is being used by another process.") when copying a file

Time:11-17

I'm using the System.IO.FileWatcher to archive incoming files of a directory. It creates a copy of a newly created file in a different folder. Here is my code:

private static async Task ArchiveFile(string filePath)
{
    await Task.Run(async () =>
    {
        try
        {
            var fileName = DateTime.Now.ToString("yyMMdd-HHmmss_", null)   Path.GetFileName(filePath);

            using Stream source = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); // <- Exception is thrown here.
            using Stream destination = new FileStream(Path.Combine(StringHelper.ArchivePath, fileName), FileMode.Create);

            await source.CopyToAsync(destination);
            Console.WriteLine($"Added file '{fileName}' to archive.");

            source.Close();
            source.Dispose();
            destination.Close();
            destination.Dispose();
        }
        catch(IOException e)
        {
            Console.WriteLine(e.Message);
        }
    });
}

Everything works just fine even though the Exception "The process cannot access the file 'C:/files/images/image.jpg' because it is being used by another process." is always thrown, while reading the file.

I expect no exception here, since the code works perfectly fine.

CodePudding user response:

It could be that the file is not fully created yet, example the file is still being copied/created to your source destination. So when you try to read from it, you get the file access error. So you can check if you can read the file and if not wait a second and try again.

while (!CanReadFile(Path.Combine(filepath, filename)))
    await Task.Delay(1000);

Your CanReadFile method will look something like this:

private bool CanReadFile(string path)
{
    try
    {
        using (var unused = File.OpenRead(path)) { }
    }
    catch (IOException ex)
    {
        if (IsFileLocked(ex))
        {
            return false;
        }
    }
    return true;
}
  • Related