C# 后期绑定和文件异常

C# late binding and File exceptions

简单的主机应用程序通过特殊接口搜索程序集并从中导入委托列表,现在是 Func<string,string>。 然后它可以执行任何 Func<T,T> 并且没有问题。 当此 Func 中的任何一个试图访问不存在的文件时,问题就开始了。

没有 try-catch 块,没有 File.Exists 没有帮助 — 当函数尝试访问文件(无论如何,读取、获取流、检查等)时 — 整个应用程序失败 FileNotFoundmscorlib 中。

如何解决这个问题?应用程序真的很关键,我不能在应用程序中执行文件检查,只能在程序集中执行。

UPD:是的,代表包含 async 逻辑。

UPD2:部分代码:

    try
    {
        if(!File.Exists(filePath)) return null;

                using (StreamWriter writer = new StreamWriter(destinationFilePath))
                {
                    using (StreamReader reader = new StreamReader(filePath))
                    {
                    //some logic there
                    }
                 }
     }
    catch 
    {

    }

在 File.Exists() 抛出异常。

此代码用于导入程序集。

Commands = new Dictionary<string, Func<string, string>>(); 
foreach (string f in fileNames)
                {

                    Assembly asm = Assembly.LoadFrom(f);
                    var types = asm.GetTypes();
                    foreach(Type t in types)
                    {

                        if (t.GetInterface("IMountPoint") != null)
                        {

                            var obj = Activator.CreateInstance(t);
                            var cmds = ((IMountPoint)obj).Init(EntryPoint);
                            foreach (var cmd in cmds)
                            {
                                if (!Commands.ContainsKey(cmd.Key.Trim().ToUpper()))
                                {
                                    Commands.Add(cmd.Key.Trim().ToUpper(), cmd.Value);
                                }

                            }
                        }
                    }
                }

并且此代码 运行 代表:

string input = Console.ReadLine();
string res = Commands[command_key](input);

太丢人了。 我正在使用后期绑定并忘记手动复制程序集,因此具有文件存在性检查的程序集不会被应用程序加载并且它使用旧的。 对不起,伙计们。