我开发了一个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/