我开发了一个用于监控文件夹的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;
}
}
}
答案 0 :(得分:3)
我遇到了同样的问题。我不喜欢我的解决方案,因为它感觉很乱。但它的确有效:
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.
}
答案 1 :(得分:1)
解决这个问题的方法不是很好。如果您在另一个应用程序想要写入文件时将文件复制到新位置,程序应该如何运作?
如果您愿意复制损坏的文件(在复制时写入),则必须编写自己的使用FileShare.ReadWrite
的复制方法。