C#中“未找到网络路径”和“拒绝访问”之间的区别
发布时间:2020-12-16 01:32:33 所属栏目:百科 来源:网络整理
导读:在我的C#.NET 2.0应用程序中,我正在访问网络路径,并且我希望能够区分不存在的路径和确实存在但我没有访问权限的路径.我尝试过以下操作: try{ string[] contents = Directory.GetFileSystemEntries( path );}catch( Exception e ){ if( e is DirectoryNotFou
在我的C#.NET 2.0应用程序中,我正在访问网络路径,并且我希望能够区分不存在的路径和确实存在但我没有访问权限的路径.我尝试过以下操作:
try { string[] contents = Directory.GetFileSystemEntries( path ); } catch( Exception e ) { if( e is DirectoryNotFoundException ) MessageBox.Show( "Path not found" ); else MessageBox.Show( "Access denied" ); } 这适用于本地路径,但对于网络路径,异常始终是System.IO.IOException,无论错误原因如何.异常消息字段根据路径是否存在显示不同的消息,所以很明显信息在某些时候可用,但我无法实现.有没有办法区分网络路径的“未找到路径”和“拒绝访问”? 编辑:所以,如果其他人想要快速解决这个问题,如henrik建议,并纳入peSHIr的建议,这里是你可以做的: try { // Issue this call just to find out whether the path exists // We don't care about the result string[] contents = Directory.GetFileSystemEntries( path ); // If we get this far then the path exists. } catch( IOException e ) { uint error = (uint)Marshal.GetHRForException( e ); if( error == (uint)0x80070041 ) // ERROR_NETWORK_ACCESS_DENIED { // The poor deluded user doesn't have access rights this.SuperProprietaryTechniqueForGettingAccessRights(); } else { // Hah! The idiot user specified a path that doesn't exist! // Chastise them severely,like all good GUI should. MessageBox.Show( "NO! BAD USER!" ); } } catch { // Swallow all other types of exception - we only made the call // to find out whether the path exists. } 解决方法
您可以调用Marshal.GetHRForException来获取更详细的信息,如:
if (Marshal.GetHRForException(e) == unchecked((int)0x800704cf)) // ERROR_NETWORK_UNREACHABLE 有关错误代码,请参阅WinError.h. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |