我有一个用 Powershell 编写的脚本,它通过 FTP 传输文件,使用以下命令可以正常工作:
$content = [System.IO.File]::ReadAllBytes($backup_app_data)
但是,一旦文件大小达到 2Gb,此方法就会停止工作,并抛出错误,指出此方法仅限于读取达到此大小的文件。
使用“1”个参数调用“ReadAllBytes”时出现异常:“该文件是
太长。该操作目前仅限于支持文件较少
大小超过 2 GB。
现在,我正在尝试修改我的脚本并使用另一种方法Read https://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx,据我了解,这将允许我分块读取文件,然后写入这些块等等。
不幸的是,尽管我修改过的脚本似乎可以正常工作,但由于在我的 FTP 位置上创建了一个文件,因此没有传输任何数据,并且脚本也没有抛出任何错误。
目标文件夹中仅创建了一个 0kb 文件,脚本结束。
我尝试进行一些调试,但似乎找不到问题所在。下面是我当前正在使用的代码。
$file = 'G:\Backups\DATA_backup_2016_09_05.zip'
$dest_name = 'DATA_backup_2016_09_05.zip'
$ftp = [System.Net.FtpWebRequest]::Create($ftp+$dest_name)
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential($user, $pass)
$ftp.UseBinary = $true
$ftp.UsePassive = $true
# determine the size of the file
$file_size = (Get-Item $file).length
$chunk_size = 512mb
$bytes_to_read = $file_size
$iterations = $file_size / $chunk_size
$iter = 0
$fstream = [System.IO.FileStream]
[byte[]] $byte_array
while ($bytes_to_read > 0){
if($iterations > 1) {
$content = $fstream.Read($byte_array, $iter, $chunk_size)
}
else {
$content = $fstream.Read($byte_array, $iter, $bytes_to_read)
}
$ftp.ContentLength = $content.Length
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
# keep the loop going
$iter = $iter + 1
$iterations = $iterations - 1
$bytes_to_read = $bytes_to_read - $chunk_size
}
$rs.Close()
$rs.Dispose()
任何帮助表示赞赏。