c# - 如何避免 Filewatcher 在 System.IO.File.Copy 期间锁定文件

标签 c# asp.net file .net

我开发了一个filewatcher程序来监视文件夹,如果文件有任何更改,它会将文件复制到另一个文件夹。

但是我发现在写入原始文件时会出现错误消息(例如文件正在被另一个应用程序处理......)似乎在运行[System.IO.File.Copy]复制到另一个文件夹时文件被锁定.

有什么解决方案可以避免原始文件被filewatcher/System.IO.File.Copy锁定吗?谢谢。

以下是我的代码:

    private void fileWatcher_Changed(object sender, System.IO.FileSystemEventArgs e)
    {
        DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath); 

        if (lastWriteTime != lastRead)
        {


            txtLog.Text += e.ChangeType + ": " + e.FullPath + "\r\n";
            txtLog.Focus();
            txtLog.Select(txtLog.TextLength, 0);
            txtLog.ScrollToCaret();

            try
            {
                string myPath = e.FullPath;
                string myFile = e.Name;

                System.IO.FileInfo myFileInfo = new System.IO.FileInfo(myFile);

                string myAttibs = myFileInfo.Attributes.ToString();

                System.IO.File.Copy(myPath, @"D:\\Folder\\Output\\" + myFile, true);

                lastRead = lastWriteTime; 

            }
            catch (System.IO.IOException ex)
            {
                System.IO.IOException myex = ex;
            }
            catch (System.Exception ex)
            {
                System.Exception myex = ex;
            }

        }
    }

最佳答案

我也遇到了同样的问题。我不喜欢我的解决方案,因为它感觉很黑客。但它有效:

FileSystemWatcher fsWatcher = new FileSystemWatcher();
fsWatcher.Created += new FileSystemEventHandler( fsWatcher_Created );

private void fsWatcher_Created( object sender, FileSystemEventArgs e )
{
    RaiseFileFoundEvent( e.FullPath );
    while ( !TestOpen( e.FullPath ) ) ;
    RaiseFileCopyDoneEvent( e.FullPath );
}

private bool TestOpen( string filename )
{
    try
    {
        FileStream fs = new FileStream( filename, FileMode.Open, 
            FileAccess.Write, FileShare.None );
        fs.Close();
        return true;
    }
    catch ( Exception )
    {
        return false;
    }
}

private void RaiseFileFoundEvent( string fullPath )
{
    // a file is found, but the copy is not guaranteed to be finished yet.
}

private void RaiseFileCopyDoneEvent( string fullPath )
{
    // the file is found, and we know the copy is done.
}

关于c# - 如何避免 Filewatcher 在 System.IO.File.Copy 期间锁定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10639298/

相关文章:

linux - 将数据流式传输到 Linux 设备驱动程序中的文件中

c# - 从 Visual Studio 启动时,WPF 应用程序加载初始窗口的速度非常慢

c# - 打破 ASP.NET 中文件背后的大型代码

javascript - 如何通过javascript更新asp.net中现有的cookie

java - java中只写行尾

c - 如何将十六进制数读入 C 中的无符号整数

c# - 无法删除用户外部登录

c# - .Net Core IsAuthenticated false 即使我手动使用 HttpContext.SignInAsync

c# - SetBinding() 和 Property={Binding Path} 的区别

c# - .net Framework 4.0 中地理 sql server 数据类型的 C# 等价物是什么?