How to test if a file is currently being written to

后端 未结 9 1748
野性不改
野性不改 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:23

    The only thing I can think of is that a file lock will be put on the file while it is being written to, therefore preventing you from writing to it (throwing a System.IO exception of file being locked by another process), but this is not foolproof. For example, the file could be written to in chunks by opening and closing the file for each chunk.

    So you could do this with a try/catch block:

    try
    {
       //opening the file
    } 
    catch(IOException ex)
    {
       // file is open by another process
    }
    

提交回复
热议问题