c# - 在反射方法调用中访问网络共享

标签 c# reflection

我们有一个访问网络共享的方法。该方法在直接调用时工作正常,但在通过反射调用时我们会得到一个 System.IO.IOException。用户上下文似乎对反射(reflect)的代码不可用(请参阅下面的堆栈跟踪)。有办法避免这种情况吗?

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)

这行得通

   Library.Class obj =new Library.Class();
   obj.Execute(serverPath);

这行不通

    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);

其中 Library.Class.execute 定义为

public void Execute(string serverPath){
   string[] directories = Directory.GetDirectories(serverPath, 
                          "1.*", SearchOption.TopDirectoryOnly);
    foreach (var directory in directories) {
        Console.WriteLine(directory);    
    }
}

serverPath 是需要用户输入凭据的网络共享。

-----更新 1--------

这似乎有点环保——我至少有一台测试机一切正常。我将进行更多测试以确定重要的差异。

最佳答案

你可能想尝试这些来获取当前目录:

AppDomain.CurrentDomain.BaseDirectory

System.Reflection.Assembly.GetExecutingAssembly().Location

关于c# - 在反射方法调用中访问网络共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7840463/

相关文章:

reflection - 神秘的类型断言失败?

C++ 使用 boost fusion adapt_struct 迭代到嵌套结构字段

reflection - 案例类上的 `productElement(i)`是否使用反射?

c# - 在 Windows Phone 8.1 应用程序中过滤 ListView

c# - 数据源上的 Kendo TreeView 同步方法不起作用

c# - 调用 FFMPEG 从 Flash 电影创建缩略图时出错

c# - 确定一个类是否实现了一个非常具体的接口(interface)

kotlin - 在 Kotlin 中遍历单例属性的正确方法是什么?

c# - 为什么释放鼠标按钮时绘制的线会消失?

c# - 并发集合上泛型参数的线程安全问题