Cant upload emtpy file to FTP through powershell

chetan Vishwakarma 146 Reputation points
2021-10-28T10:14:53.523+00:00

Hello Team ,

I am uploading files to ftp server but due to some reason if file is empty at source then it is throwing me below error
Could you please help me to get this resolve?

Exception calling "Write" with "3" argument(s): "Value cannot be null.
Parameter name: buffer"
At C:\Chetan\Powershell-Scripts\SFTPFileCheck1.10.ps1:256 char:17

  • $run.Write($filecontent, 0, $filecontent.Length)
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
  • FullyQualifiedErrorId : ArgumentNullException

Here is the code below :
$ftprequest = [System.Net.FtpWebRequest]::Create("$RemoteLocation1")
$ftprequest = [System.Net.FtpWebRequest]$ftprequest
$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftprequest.Credentials = new-object System.Net.NetworkCredential($SFTPUser, $Pass)
$ftprequest.UseBinary = $true
$ftprequest.UsePassive = $true
$ftprequest.EnableSsl = $true
$filecontent = gc -en byte $Source1
$ftprequest.ContentLength = $filecontent.Length
$run = $ftprequest.GetRequestStream()
$run.Write($filecontent, 0, $filecontent.Length)
$run.Close()
$run.Dispose()

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 48,036 Reputation points
    2021-10-28T19:19:37.487+00:00

    Well, this statement $filecontent = gc -en byte $Source1 leaves the variable $filecontent with a value of "$null". In other words, there's nothing there.

    You can try adding this after the "$filecontent = gc -en byte $Source1" in your script:

    if(-not $filecontent){
        $filecontent = [Byte[]]""
    }
    
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.