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?

Ralph Willgoss
  • 11,750
  • 4
  • 64
  • 67
  • Related: http://stackoverflow.com/questions/12870109/how-do-i-call-new-object-for-a-constructor-which-takes-a-single-array-parameter – David Brabant Dec 05 '14 at 09:55

1 Answers1

3

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.

Ralph Willgoss
  • 11,750
  • 4
  • 64
  • 67
DanL
  • 1,974
  • 14
  • 13
  • Your first suggestion worked perfectly - why? I had tried the second option by itself before and it did not work. – Ralph Willgoss Dec 05 '14 at 10:12
  • 1
    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 – DanL Dec 05 '14 at 10:25