Home > Net >  using assembly.load with a specific file location
using assembly.load with a specific file location

Time:02-01

I have the current file structure in my Visual Studio project:

  • MyProject/
    • MyStartupProject/
      • bin/
        • Debug/
      • Program.cs
    • DependencyProject/
      • bin/
      • dlls/
        • MyAssembly.dll
      • Code.cs

My Main() function is inside MyProject/MyStartupProject/Program.cs. Inside Code.cs is a line var assembly = Assembly.Load("MyAssembly");, which is supposed to load MyProject/DependencyProject/dlls/MyAssembly.dll, but instead it causes the error

System.IO.FileNotFoundException: 'Could not load file or assembly 'MyAssembly' or one of its dependencies.
The system cannot find the file specified.'

However, everything runs perfectly fine if I copy MyAssembly.dll into MyProject/MyStartupProject/bin/Debug. How do I fix this reference so the project can find it under the dlls directory?

CodePudding user response:

I resolved my issue by adding the following to my DependencyProject.csproj

<ContentWithTargetPath Include="dlls\MyAssembly.dll">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <TargetPath>MyAssembly.dll</TargetPath>
</ContentWithTargetPath>

This causes the dlls to be automatically copied into MyStartupProject/bin/Debug/.

CodePudding user response:

Try to Change the status of MyAssembly.dll to Copy if new.

enter image description here

Update:

enter image description here

Add file

enter image description here

enter image description here

Update2:Is there a way I can get it to copy straight into Debug/ without moving the original out of the dlls/ directory?

Two solutions:

  1. Change var assembly = Assembly.Load("MyAssembly"); to var assembly = Assembly.LoadFrom("dlls\MyAssembly.dll");.

  2. enter image description here

    2.Double-click Project:

    enter image description here

  •  Tags:  
  • Related