与后台工作者的Windows服务无法加载文件或程序集错误

问题描述:

我正在创建一个Windows服务,它测试是否可以执行预定作业,然后启动后台工作来执行作业。与后台工作者的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 \目录下。

+0

*在DAL的方法从组件*加载一个SQL文件 - 这是什么意思? SQL文件是否被编译到程序集中? – 2014-10-17 09:30:12

这可能会解决这个问题:

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

-1这不是由编码问题引起的 - 问题在于程序集绑定解析。 – 2014-10-17 09:37:24

+0

@TomRedfern。我怀疑这**是一个编码问题。一个服务的当前目录将是c:\ windows \ system32,因此我怀疑程序(使用Assembly.LoadFrom)只是在当前目录中查找dll。如果是这样,那么这可能会解决这个问题。另一种方法是更改​​Assembly.LoadFrom以从正确的目录加载文件。 – sgmoore 2014-10-17 09:52:51

+0

根据@ sgmoore的评论重新阅读这个问题后,我承认在我最初对可口可乐回答的评估中我错误了。道歉! - 不幸的是我不能撤消我的投票,除非你更新你的答案... – 2014-10-17 10:08:48