Aar*_*her 8 c# vb.net .net-3.5
我有一个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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 -2
查找您可以处理的显式错误代码,例如:
catch (Exception u) { if (((SocketException)u).ErrorCode == 10035) ...
看看这里: http://msdn.microsoft.com/en-us/library/ms681391 (VS.85).aspx
对于错误代码,例如:
错误共享违规 - 32 - 0x20
错误_访问_拒绝 = 5 - 0x5
错误_文件_未找到 - 2 - 0x2
| 归档时间: |
|
| 查看次数: |
6797 次 |
| 最近记录: |