如何在C#中检测截断的文件

时间:2008-11-10 18:46:41

标签: c# .net

如果我在共享访问模式下读取文本文件而另一个进程截断它,那么检测它的最简单方法是什么? (我排除了定期刷新FileInfo对象以检查其大小的明显选择)是否有一些方便的方法来捕获事件? (Filewatcher?)

3 个答案:

答案 0 :(得分:3)

有,它被称为FileSystemWatcher

如果您正在开发Windows窗体应用程序,可以从工具箱中拖放它。

以下是一些使用示例:

private void myForm_Load(object sender, EventArgs e)
{
    var fileWatcher = new System.IO.FileSystemWatcher();

    // Monitor changes to PNG files in C:\temp and subdirectories
    fileWatcher.Path = @"C:\temp";
    fileWatcher.IncludeSubdirectories = true;
    fileWatcher.Filter = @"*.png";

    // Attach event handlers to handle each file system events
    fileWatcher.Changed += fileChanged;
    fileWatcher.Created += fileCreated;
    fileWatcher.Renamed += fileRenamed;

    // Start monitoring!
    fileWatcher.EnableRaisingEvents = true;
}

void fileRenamed(object sender, System.IO.FileSystemEventArgs e)
{
    // a file has been renamed!
}

void fileCreated(object sender, System.IO.FileSystemEventArgs e)
{
    // a file has been created!
}

void fileChanged(object sender, System.IO.FileSystemEventArgs e)
{
    // a file is modified!
}

它位于System.IO和System.dll中,因此您应该能够在大多数类型的项目中使用它。

答案 1 :(得分:3)

FSW无法可靠地工作,它是异步的。假设您没有收到异常,StreamReader.ReadLine()将在文件被截断时返回null。然后检查尺寸是否改变。要注意不可避免的竞争条件,你需要验证关于时间的假设。

答案 2 :(得分:0)

只是要咀嚼的东西;它可能不适用于您的情况:

chakrit的解决方案对于您的要求是正确的,但我不得不问 - 为什么在另一个进程截断它的同时读取文件?

特别是,如果你没有同步,同时读/写文件并不是特别安全,你可能会发现还有其他神秘问题。