当FtpWebRequest停止时,超时FTP上传



所以我有一个简单的FTP上传脚本,它循环遍历要上传的一组文件。循环选择一个文件(排序的gci数组)上传它,然后移动到下一个。总共约20个文件。当我从服务器得到一个错误或者当我从服务器得到一个上传完成的确认时,单个文件的循环结束。

最近,服务器两个都不给我,允许上传通过,但不确认文件已经完成。这意味着脚本会在循环中卡住几个小时,直到我手动关闭脚本。

我希望在主上传命令上设置一个超时:

$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)

看起来好像写命令,虽然文件已经完全写在目标FTP服务器上,但从来没有从FTP服务器得到响应,这意味着它只是挂起,挂起,挂起。

我希望做的是添加一个超时。这里的挑战是,我不知道有什么方法可以在执行"写"的过程中检查计时器。工作。

这里有选项吗?

这就是我要做的,但似乎(我的猜测),因为定时器从来没有在写作业中间相互比较,循环不会退出,直到re.write作业完成(这可能永远不会)

有什么想法吗?

$timeout = New-TimeSpan -Seconds 8
$timer = [System.Diagnostics.Stopwatch]::StartNew()
do {
# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create($ftpdestination)
$ftp = [System.Net.FtpWebRequest]$ftp
# build authentication and connection
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential($username,$password)
$ftp.UseBinary = $true
$ftp.UsePassive = $true
$ftp.timeout = -1
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes($sourcefile)
$ftp.ContentLength = $content.Length
# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
$rs.Close()
$rs.Dispose()
}
while ($timer.Elapsed -lt $timeout)

所以这就是我使用的,然而,我得到的问题是,在rs.write期间(我所有的时间都在那里),它没有重新评估($timer.Elapsed -lt $timeout)方程,所以它没有停止。这就是我卡住的地方。

您的问题是$ftp.timeout = -1-1表示"无限"。参见FtpWebRequest.Timeout属性文档中的备注部分

设置一个合理的值

最新更新