How to test if a file is currently being written to

后端 未结 9 1650
野性不改
野性不改 2020-12-18 21:42

I have an application that must check a folder and read any files that are copied into it. How do I test if a file in that folder is currently being written to? I only want

相关标签:
9条回答
  • 2020-12-18 22:36

    When you open it with System.IO.File.OpenWrite(filename), it should throw IOException.

    So, in a try catch, the code being executed in the catch block should tell you the file was open.

    0 讨论(0)
  • 2020-12-18 22:39

    Perhaps opening the file exclusively like this -

    System.IO.File.Open(PathToFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    

    That could be placed in a loop with a try/catch until its successful.

    0 讨论(0)
  • 2020-12-18 22:42

    Number of options. The one that springs to mind straight away is to try opening the file for write. If you raise an exception, it is still being written to. Wait for a defined period and try again.

    Alternatively check the timestamps and only try reading the file 1 or 2 minutes after the timestamp last changed

    0 讨论(0)
提交回复
热议问题