Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add-Type from cs, that requires referencing assemblies

I hava a cs file with very simple code:

using Ionic.Zip;
public static class Helper
{
        public static ZipFile GetNewFile(string fileName)
        {       
            return new ZipFile(fileName);
        }
}

It requires Ionic.Zip assembly. I want to add this type to my powershell like this:

cd c:\pst
Add-Type -Path "2.cs" -ReferencedAssemblies "Ionic.Zip.dll"
$var = [Helper]::GetNewFile("aaa")

When I do this it gives me:

The following exception occurred while retrieving member "GetNewFile": "Could not load file or assembly 'Ionic.Zip, Version=1.9.1.8, Culture=neutral, PublicKeyToken=edbe51ad942a3f5c' or one of its dependencies. The located assembly'
s manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)"

It seems to have compiled assembly in some temp location and it can't find Ionic.Zip there.

It works, however, if specify the output assembly and then add this assembly:

cd c:\pst
Add-Type -Path "2.cs" -ReferencedAssemblies "Ionic.Zip.dll" -OutputAssembly "T.dll"
Add-Type -Path "T.dll"

$var = [Helper]::GetNewFile("aaa")
$var.AlternateEncoding

So I'm wondering if there's a way to avoid usage of output assembly?

like image 473
Andrey Marchuk Avatar asked Nov 24 '11 08:11

Andrey Marchuk


People also ask

How do I reference an assembly in C#?

In the Project Designer, click the References tab. Click the Add button to open the Add Reference dialog box. In the Add Reference dialog box, select the tab indicating the type of component you want to reference. Select the components you want to reference, and then click OK.

What does add-type do in PowerShell?

The Add-Type cmdlet lets you define a Microsoft . NET Core class in your PowerShell session. You can then instantiate objects, by using the New-Object cmdlet, and use the objects just as you would use any .

Is defined in an assembly that is not referenced?

When you get this error, it means that code you are using makes a reference to a type that is in an assembly, but the assembly is not part of your project so it can't use it.


2 Answers

In Powershell v3 CTP1 you can resolve the full path (fullname) of your zip library and reference that:

$ziplib = (get-item ionic.zip.dll).fullname
[void][reflection.assembly]::LoadFrom($ziplib)
Add-Type -Path "2.cs" -ReferencedAssemblies $ziplib
$var = [Helper]::GetNewFile("aaa")
$var.AlternateEncoding
like image 174
jon Z Avatar answered Oct 06 '22 02:10

jon Z


You have to put your ionic.zip.dll file in the GAC then on powershell you can do this:

C:\ps> [System.Reflection.Assembly]::LoadWithPartialName("ionic.zip")
C:\ps> Add-Type -Path "2.cs" -ReferencedAssemblies "Ionic.Zip.dll"
C:\ps> $var = [Helper]::GetNewFile("aaa")
C:\ps> $var.name
aaa
like image 27
CB. Avatar answered Oct 06 '22 02:10

CB.