1

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.

5
  • So what makes you think the error is incorrect? Perhaps use something like Process Explorer to find out what's locking the file? Commented Nov 17, 2022 at 8:09
  • The file is obviously being accessed here, yet this exception is caught. The file is being archived successfully. "Copy" is not the problem here. It is read that causes this. Commented Nov 17, 2022 at 8:12
  • Your statement is contradictory. You assert that it is being archived successfully (i.e. it is being read and its bytes are being written into a new file), but you also say that you can't read the file because of this error. How can both be true? Commented Nov 17, 2022 at 8:16
  • Well, thats is the problem I'm trying to explain. Commented Nov 17, 2022 at 8:20
  • But you say that the exception occurs before you even interact with the file system to make the archive file. You are mistaken in your beliefs about what is happening. Commented Nov 17, 2022 at 8:20

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Seems to be the case here. A bit of a squirly workaround, but this will do. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.