gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:07:10 25 4
gpt4 key购买 nike

我开发了一个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# - 如何在 System.IO.File.Copy 期间避免 Filewatcher 锁定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10639298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com