FileSystemWatcher - is File ready to use

后端 未结 6 1012
[愿得一人]
[愿得一人] 2020-12-03 17:45

When a file is being copied to the file watcher folder, how can I identify whether the file is completely copied and ready to use? Because I am getting multiple events duri

6条回答
  •  离开以前
    2020-12-03 18:38

        private Stream ReadWhenAvailable(FileInfo finfo, TimeSpan? ts = null) => Task.Run(() =>
        {
            ts = ts == null ? new TimeSpan(long.MaxValue) : ts;
            var start = DateTime.Now;
            while (DateTime.Now - start < ts)
            {
                Thread.Sleep(200);
                try
                {
                    return new FileStream(finfo.FullName, FileMode.Open);
                }
                catch { }
            }
            return null;
        })
        .Result;
    

    ...of course, you can modify aspects of this to suit your needs.

提交回复
热议问题