我有一个 C# 应用程序,我想将文件复制到新位置。有时我需要覆盖现有文件。
当发生这种情况时,我收到 System.IO.IOException。我想从共享冲突中恢复,但如何确定返回 IOException 是因为目标文件正在使用而不是其他原因?我可以查找“该进程无法访问该文件,因为它正在被另一个进程使用。”消息...但我不喜欢这个主意。
这是我想出的解决方案。
private void RobustMoveFile( System.IO.DirectoryInfo destinationDirectory, System.IO.FileInfo sourceFile, Boolean retryMove )
{
try
{
string DestinationFile = Path.Combine( destinationDirectory.FullName, sourceFile.Name );
if ( File.Exists( DestinationFile ) )
sourceFile.Replace( DestinationFile, DestinationFile + "Back", true );
else
{
sourceFile.CopyTo( DestinationFile, true );
sourceFile.Delete();
}
}
catch ( System.IO.IOException IOEx )
{
int HResult = System.Runtime.InteropServices.Marshal.GetHRForException( IOEx );
const int SharingViolation = 32;
if ( ( HResult & 0xFFFF ) == SharingViolation && retryMove )
RobustMoveFile( destinationDirectory, sourceFile, false );
throw;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)