2

I am trying to load the binary contents of a file into ByteArrayContent using the following powershell:

$arr = Get-Content $pathToFile -Encoding Byte -ReadCount 0
$binaryContent = New-Object System.Net.Http.ByteArrayContent($arr)

I receive the following error when the script is ran:

Cannot find an overload for "ByteArrayContent" and the argument count: "460"

I'm running this script on Windows 8.1, using Powershell 4.0.

Checking the documentation there are two overloads for ByteArrayContent, I'm using the first so I ensured that I'm parsing a byte[] array to the ctor.

In the end I used the other ctor and everything worked:

$binaryContent = New-Object System.Net.Http.ByteArrayContent($arr, 0, $arr.Length)

I checked the version of the System.Net.Http assembly I am using, by running the following command to see all the loaded assemblies:

[System.AppDomain]::CurrentDomain.GetAssemblies()
v4.0.30319 => C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Net.Http\v4.0_4.0.0.0

In the MSDN documentation I can't see any other versions of the ByteArrayContent, so any ideas on what describes this behaviour?

1

1 Answer 1

4

Could you either replace

$binaryContent = New-Object System.Net.Http.ByteArrayContent($arr)

with

$binaryContent = New-Object System.Net.Http.ByteArrayContent -ArgumentList @(,$arr)

or change the line:

$arr = Get-Content $pathToFile -Encoding Byte -ReadCount 0

to

[byte[]]$arr = Get-Content $pathToFile -Encoding Byte -ReadCount 0


Explanation
Powershell is usually expecting an array of arguments to find the right constructor to call. In your case, it seen the byte array as 460 separate arguments.

By using @(,$arr), we then have an array with one element, that one element is an array itself but it is enough for powershell to consider the constructor which uses a byte array.

Sign up to request clarification or add additional context in comments.

3 Comments

Your first suggestion worked perfectly - why? I had tried the second option by itself before and it did not work.
Hi Ralph, I don't fully understand the exact principals that Powershell uses for resolving which methods to use. However, powershell is usually expecting an array of arguments to find the right constructor to call. In your case, it seen the byte array as 460 separate arguments. By using @(,$arr), we then have an array with one element, that one element is an array itself but it is enough for powershell to consider the constructor which uses a byte array
I can confirm it. The second option with [byte[]]$arr (which I've tried already earlier) did not work by me either. The first option did the job. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.