Search code examples
c#streamreader

Read from file without blocking it from being deleted


I'm writing a windows service that reads from a file share on the network. Sometimes files are written to the file share and then deleted in very quick succession. Is there a way that I can read the file while also allowing the file to be deleted?

Basically I've got a filesystemwatcher watching the network path and then on the Created event for that directory I check the filepath and then try to read the file on a new thread. When the app that writes the file to the directory tries to delete it quickly, it gets IOException saying there's another process using the file. I didn't write the app on the network computer and don't want to interrupt its normal function

Here's my code

public async Task Copy(string src, string dest) {
    using (FileStream srcReader = File.Open(src, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (Stream destWriter = File.Create(dest)) {
       await srcReader.CopyToAsync(destWriter, cancelToken);
}

Solution

  • FileShare has a Delete flag. So try this:

    File.Open(
        src, 
        FileMode.Open, 
        FileAccess.Read, 
        FileShare.ReadWrite | FileShare.Delete
    )