How to test if a file is fully copied in .NET

后端 未结 9 1271
小鲜肉
小鲜肉 2021-01-17 12:27

I am monitoring a folder for new files and need to process them. The problem is that occasionally file opening fails, because system has not finished copying it.

Wha

9条回答
  •  粉色の甜心
    2021-01-17 12:35

    In fact, to avoid race conditions, the only safe solution is to retry.

    If you do something like:

    while (file is locked)
        no-op()
    process file()
    

    You risk another process jumping in between the while guard and the process file statement. No matter how your "wait for file availability" is implemented, unless you can ensure that post-unlock you're the first process to access it, you might not be that first user.

    This is more likely that might seem at first glance, in particular if multiple people are watching the file, and in particular if they're using something like the file-system watcher. Course, it's still not particularly likely even then...

提交回复
热议问题