我们有一种访问网络共享的方法.直接调用时此方法可以正常工作,但是当通过reflecton调用它时会得到System.IO.IOException.看起来用户上下文不可用于反射代码(请参阅下面的堆栈跟踪).有办法防止这种情况吗?
System.Reflection.TargetInvocationException: Exception has been thrown by
the target of an invocation. ---> System.IO.IOException: Logon failure:
unknown user name or bad password.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.InternalGetFileDirectoryNames(String path,
String userPathOriginal, String searchPattern, Boolean includeFiles,
Boolean includeDirs, SearchOption searchOption)
at System.IO.Directory.GetDirectories(String path, String searchPattern,
SearchOption searchOption)
Run Code Online (Sandbox Code Playgroud)
这很有效
Library.Class obj =new Library.Class();
obj.Execute(serverPath);
Run Code Online (Sandbox Code Playgroud)
这不起作用
Assembly assembly = Assembly.LoadFile(@"pathTo\Library.dll");
Type type = assembly.GetType("Library.Class");
MethodInfo executeMethod = type.GetMethod("Execute");
object classInstance = Activator.CreateInstance(type, null);
object[] parameterArray = new object[] { serverPath};
executeMethod.Invoke(classInstance, parameterArray);
Run Code Online (Sandbox Code Playgroud)
其中Library.Class.execute定义为
public void Execute(string serverPath){
string[] directories = Directory.GetDirectories(serverPath,
"1.*", SearchOption.TopDirectoryOnly);
foreach (var directory in directories) {
Console.WriteLine(directory);
}
}
Run Code Online (Sandbox Code Playgroud)
并且serverPath是需要用户输入凭据的网络共享.
----- 更新1 -------
这似乎有点环保 - 我至少有一台测试机,一切正常.我将进行更多测试以确定哪些差异很重要.
| 归档时间: |
|
| 查看次数: |
747 次 |
| 最近记录: |