具有后台工作程序的windows服务无法加载文件或程序集错误

本文关键字:加载 文件 错误 程序集 服务 后台 工作程序 windows | 更新日期: 2023-09-27 18:26:48

我正在创建一个windows服务,它测试是否可以执行计划的作业,然后启动后台工作程序来执行该作业。

在windows服务的主线程中,我从与windows服务可执行文件位于同一目录中的程序集创建了一个数据访问层(DAL)对象。这是有效的。

在后台工作程序中,我还尝试创建同一对象的新实例。看起来这是成功的。DAL中的方法从程序集中加载SQL文件,然后对给定的数据库执行。

在这个过程中的某个地方,我得到了以下错误:

 System.IO.FileLoadException: Could not load file or assembly 'file:///C:'Windows'system32'DataConnector.dll' or one of its dependencies. The system cannot find the file specified.
    File name: 'file:///C:'Windows'system32'DataConnector.dll'
       at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at DataConnector.DatabaseConnector.UpdateDatabase()

我不知道后台工作人员为什么要查看C:''windows''system32''目录。

具有后台工作程序的windows服务无法加载文件或程序集错误

这可能会解决问题:

System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);