在System.IO.FileSystemWatcher中创建事件

时间:2011-08-24 11:12:12

标签: c# visual-studio-2008

我有一个文件夹。当文件复制到该文件夹​​时,我需要重命名它。因此我使用System.IO.FileSystemWatcher来做到这一点。我已经实施了一项服务来实现这一目标。

我的代码如下。

private System.IO.FileSystemWatcher FSWatcherTest;

FSWatcherTest.Created += new FileSystemEventHandler(FSWatcherTest_Created);

--------

private void FSWatcherTest_Created(object sender, System.IO.FileSystemEventArgs e)
{
    //Some code
    File.Move(oldfilepath, newfilepath);
    //some code
}

当我从本地计算机复制文本文件时,它工作正常。但是当我从网络上复制我的大文件时,这是行不通的。错误是当它被覆盖时会被触发。因此该方法无法访问该文件。但是我想知道为什么这会被它解雇。

我正在为此应用程序使用VS 2008C#

提前致谢。

2 个答案:

答案 0 :(得分:0)

Hacky解决方案:

如果无法知道文件何时完全复制,您可以继续尝试直到文件完成。

这样的事情:

private void FSWatcherTest_Created(object sender, System.IO.FileSystemEventArgs e)
{
    FileMover(object sender, System.IO.FileSystemEventArgs e);
}

private void FileMover(object sender, System.IO.FileSystemEventArgs e)
{
    try{
    //Some code
    File.Move(oldfilepath, newfilepath);
    //some code
    }
    catch
    {
         //Call an asynchronous method that will wait 1 second then call FileMover again       
         //with the same arguments,
         //a BackGroundWorker would be perfect for that job.
    }
}

答案 1 :(得分:0)

刚发现这个snippit

        Dim F As Short = FreeFile()
        FileOpen(F, sFile, OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.LockReadWrite)
        FileClose(F)

是否可以将其包装在'WHILE'循环中,以便等待复制过程免费?