Why i get blank uploaded file to ftp from powershell

i am try to upload a file to ftp via

#Unique Variables
$FTPServer = "ftp://example.com/"
$FTPUsername = "username"
$FTPPassword = "password" 
$LocalDirectory = "C:\temp\" 
$FileToUpload = "example.txt"

#Connect to the FTP Server
$ftp = [System.Net.FtpWebRequest]::create("$FTPServer/$FileToUpload")
$ftp.Credentials =  New-Object System.Net.NetworkCredential($FTPUsername,$FTPPassword)

#Upload file to FTP Server
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile

#Verify the file was uploaded
$ftp.GetResponse()

but when put this script into powershell, i get no errors, but my output file in FTP is blank. Where is problem?

Hi @mercyangel,
Based on your code you are not uploading file.
You just create an new file on the FTP side.
Please try something similar to following:

# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create("ftp://localhost/me.png")
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential("anonymous","anonymous@localhost")
$ftp.UseBinary = $true
$ftp.UsePassive = $true
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes("C:\me.png")
$ftp.ContentLength = $content.Length
# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
# be sure to clean up after ourselves
$rs.Close()
$rs.Dispose()

Reference.

Hope that helps.

1 Like