Question

UPDATE: the

$ftprespsonse = [System.Net.FtpWebResponse]$ftp.GetResponse()

in the following code creates an empty file(file with the same name but has size 0), which leads to the duplication of my original question. My question is why the GetRepsonse creates that empty file? My guess right now is the [System.Net.FtpWebRequest]::Create and GetResponse will mess up stuff.

$username="user"
$password="pw"
$ftp = [System.Net.FtpWebRequest]::Create("ftp://xxx.xxx.xxx:{port}/file.txt")
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential($username,$password)
$ftp.UseBinary = $true
$ftp.UsePassive = $true
$ftp.EnableSsl = $true
$ftp.KeepAlive = $false
$ftprespsonse = [System.Net.FtpWebResponse]$ftp.GetResponse()
$content = [System.IO.File]::ReadAllBytes("c:\file.txt")
$ftp.ContentLength = $content.Length
try
{
    $rs = $ftp.GetRequestStream()
    $rs.Write($content, 0, $content.Length)
    'File Uploaded.'
    Write-Host 'Status code: ' + $ftprespsonse.StatusCode
    Write-Host 'Status descriptionL: ' + $ftprespsonse.StatusDescription
    $ftprespsonse.close()
    $ftp.Abort()
    $rs.Close()
    $rs.Dispose()
}
catch [System.Exception]
{
    'Upload failed.'
    $ftprespsonse = [System.Net.FtpWebResponse]$ftp.GetResponse()
    Write-Host 'Status code: ' + $ftprespsonse.StatusCode
    Write-Host 'Status descriptionL: ' + $ftprespsonse.StatusDescription
    $ftprespsonse.close()
    $ftp.Abort()
}

By running this script, I can see the following output:

File Uploaded.
Status code:  + ClosingData
Status descriptionL:  + 226- Transfer complete - acknowledgment message is pending.
226- Transfer complete - acknowledgment message is pending.
226 Transfer complete (Batch Number = 30009).

And going to the remote folder, I can see that two files are created, the file names are the same, but one of them has file size 0 and the other is 570kb (which is correct).

any idea what happened?

Was it helpful?

Solution 2

It turned out the order of

$ftp = [System.Net.FtpWebRequest]::Create($fileRemotePath)

and $ftprespsonse = [System.Net.FtpWebResponse]$ftp.GetResponse()

and $rs = $ftp.GetRequestStream()

messes up the stuff. By running the code line by line, I find that the empty file is created at the first appearance of the $ftp.GetResponse() , after that, the full file is created on line $ftp.GetRequestStream()

therefore, I will move the first GetResponse() to after the GetRequestStream()

OTHER TIPS

Use Powershell FTP Module(http://gallery.technet.microsoft.com/scriptcenter/PowerShell-FTP-Client-db6fe0cb), you will sidestep having to implement your own FTP client and likely avoid your curious issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top