无法加载文件或程序集"Npgsql,版本=4.0.5.0,区域性=中性..."或其依赖项之一。仅在任务计划程序中出现



我的项目目标是从Microsoft CRM获取数据并将其上传到PostGresSQL数据库。 当我手动运行可执行文件时,一切正常,但是当我在任务计划程序上将应用程序作为计划任务运行时,出现此错误:

"无法加载文件或程序集'Npgsql,版本=4.0.5.0,区域性=中性,公钥令牌=5d8b90d52f46fda7'或其依赖项之一。 系统找不到指定的文件"。

我尝试将以下内容添加到我的.csproj文件中,但仍然没有运气

<PropertyGroup>
  <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>  
 <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>

一切正常,直到它达到下面的功能。 它不会进入该功能,因为"打印测试"永远不会在控制台中写入。

    public void upToPostgresDB(string queryString)
            {
                Console.WriteLine("Print Test");
    #if DEBUG
    //Credentials below are not actually blank, I just removed them for privacy
                String pgDatabase = "";
                String pgServer = "";
                String pgUser = "";
                String pgPass = "";
    #else
                String pgDatabase = "";
                String pgServer = "";
                String pgUser = "";
                String pgPass = "";
    #endif
                String pgConnectionString = String.Format("Server={0}; UserId={1}; Password={2}; Database={3}", pgServer, pgUser, pgPass,     pgDatabase);
            NpgsqlConnection pgCon = new NpgsqlConnection(pgConnectionString);
            NpgsqlCommand cmd = new NpgsqlCommand(queryString, pgCon);            
            try
            {
                pgCon.Open();
                cmd.ExecuteNonQuery();
                pgCon.Close();
            }
            catch (Exception e)
            {
                string errorMessage = "Failed to upload data to the postgres database.  " + e.Message;
                Console.WriteLine(errorMessage);
                pgCon.Close();
            }
        }

如果您的 .NET Framework 库也使用一些非托管代码库作为其依赖项模块,则通常会出现此异常。尝试通过以下应用程序扫描库中的依赖项:

http://www.dependencywalker.com/(对于"传统"技术和语言,如C++、OCX、OLE等;我不确定它是否适用于现在的 MS.NET(

https://www.red-gate.com/products/dotnet-development/reflector/(用于 MS.NET 模块扫描和代码反编译(

这应该指导您找到解决方案。如果它对您不起作用,那么下一步确保您已正确配置应用程序启动路径和目标路径以搜索程序集:https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/specify-assembly-location

最后一件事是将缺少的非托管代码程序集复制到包含托管包装程序集的目录中。

问题是我只将可执行文件复制并粘贴到目标文件夹。 我需要复制整个调试或发布文件夹,因为非 .NET 相关程序集往往会产生这种影响。 通过将所有依赖库与我的.exe放在同一个文件夹中,这解决了这个问题。

最新更新