如何测试,如果一个文件当前正在写入到 [英] How to test if a file is currently being written to

查看:124
本文介绍了如何测试,如果一个文件当前正在写入到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个必须检查的文件夹和读取被复制到其中的任何文件的应用程序。 如何测试,如果该文件夹中的文件,目前正在写?我只想读取文件 这不得不写信给他们所有的数据和关闭。

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 to read files that have had all their data written to them and are closed.

推荐答案

这是不干净的,但它的作品:

It ain't clean, but it works:

try
{
    using (Stream stream = new FileStream("File.txt"))
    {
    }
} 
catch 
{
    // Check if file is in use (or whatever else went wrong), and do any user communication that you need to
}

我特别不喜欢使用异常的情况,但据我所知,这是要做到这一点,最简单,最好的(也是唯一可靠)的方式。

I don't particularly like using exceptions as conditions, but as far as I know this is about the easiest and best (and only reliable) way to do this.

这篇关于如何测试,如果一个文件当前正在写入到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆