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.