问题
We are trying to copy a file from a server, down to a local machine in a .NET 2.0 application (C#), but keep having the source file unnecessarily locked. We suspect it is something configured on the file server that is causing this behaviour, but are not sure what ... can you help?
After the file copy operation, the file server (Windows 2K3 R2) reports that the source file is being held with a read lock, even though no further operation is done with the file on the server. The lock is released once the application quits.
We are able to reproduce the behaviour, even with the most basic code seen below :
static void Main(string[] args)
{
string sourceFile = @"\\win2K3server\resource\Production\IQE\sourceFolder\iqeconsole.exe";
string destinationFile = @"d:\destinationFolder\iqeconsole.exe";
System.IO.File.Copy(sourceFile,destinationFile,true);
Console.ReadLine();
}
The lock occurrs immediately during the File.Copy()
line executing, and persists after this line has finished. In a more complex application, when the routine with the File.Copy()
exits(but the application is still running), the lock persists.
Only when the entire application is finished is the lock released.
Changing sourceFile
to use a mapped drive instead of a UNC path makes no difference to the behaviour.
This behaviour does not happen when the source file is located on another server, or is located locally.
If we add the following line after the File.Copy
, the lock is released immediately :
new System.Security.Permissions.FileIOPermission(System.Security.Permissions.FileIOPermissionAccess.Read, new string[] { sourceFile }).Demand();
This all sounds to us as though there is something on the server that is causing this behaviour. We have ShadowProtect installed on the server along with McAfee anti-virus. Apart from that, it appears as though there is nothing else installed over-and-above Windows Server and its components.
We are also not sure why Demanding a read permission on the file solves the problem.
If you could answer these questions, we would appreciate it greatly:
- What is causing the file locks to persist?
- Why does Demanding a read permission solve the problem?
回答1:
It is probably the McAfee on-access scanner that holds the lock. If you only use read access, it is bypassed. I believe that you can use the Sysinternals Process Viewer tool (free from Microsoft) to confirm that.
Not sure what subscription you have for McAfee, but you can define exception rules so that it does not scan this file.
回答2:
I am not able to replicate this on our file servers.
However, I do know Opportunistic locking is disabled since we're using PeerLock by PeerSoftware.
来源:https://stackoverflow.com/questions/603444/file-copy-locks-source-file-after-completion