Monitoring files - how to know when a file is complete

前端 未结 9 2040
无人及你
无人及你 2021-01-11 12:59

We have several .NET applications that monitor a directory for new files, using FileSystemWatcher. The files are copied from another location, uploaded via FTP, etc. When th

9条回答
  •  南方客
    南方客 (楼主)
    2021-01-11 13:39

    The following method tries to open a file with write permissions. It will block execution until a file is completely written to disk:

    /// 
    /// Waits until a file can be opened with write permission
    /// 
    public static void WaitReady(string fileName)
    {
        while (true)
        {
            try
            {
                using (System.IO.Stream stream = System.IO.File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    if (stream != null)
                    {
                        System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} ready.", fileName));
                        break;
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} not yet ready ({1})", fileName, ex.Message));
            }
            catch (IOException ex)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} not yet ready ({1})", fileName, ex.Message));
            }
            catch (UnauthorizedAccessException ex)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} not yet ready ({1})", fileName, ex.Message));
            }
            Thread.Sleep(500);
        }
    }
    

    (from my answer to a related question)

提交回复
热议问题