![](/img/trans.png)
[英]How Can I optimize my FTP Download using foreach() and ftpwebrequest?
[英]How to download files that contain a pound/hash sign '#' in the filename from an FTP server using PowerShell's FtpWebRequest class
我已經構建了一個用於從 FTP 服務器下載文件的腳本。 該腳本適用於我嘗試下載的所有文件,但包含#
文件除外。 在做了一些研究之后,我無法找到解決這個問題的方法。 下面列出了我下載文件的代碼。
function Get-FtpFile
{
Param ([string]$fileUrl, $credentials, [string]$destination)
try
{
$FTPRequest = [System.Net.FtpWebRequest]::Create($fileUrl)
if ($credentials)
{
$FTPRequest.Credentials = $credentials
}
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$FTPRequest.UseBinary = $true
# Send the ftp request
$FTPResponse = $FTPRequest.GetResponse()
# Get a download stream from the server response
$ResponseStream = $FTPResponse.GetResponseStream()
# Create the target file on the local system and the download buffer
$LocalFile = New-Object IO.FileStream ($destination,[IO.FileMode]::Create)
[byte[]]$ReadBuffer = New-Object byte[] 1024
# Loop through the download
do {
$ReadLength = $ResponseStream.Read($ReadBuffer,0,1024)
$LocalFile.Write($ReadBuffer,0,$ReadLength)
}
while ($ReadLength -ne 0)
$LocalFile.Close()
}
catch [Net.WebException]
{
return "Unable to download because: $($_.exception)"
}
}
我嘗試使用WebRequest.DownloadFile()
代替,但它仍然不適用於包含#
文件,我也嘗試使用FtpWebRequest
重命名方法重命名文件,但也不起作用。
有誰知道這個問題的任何解決方案或解決方法?
您必須在 URL ( $fileUrl
) 中將#
編碼為%23
。
如果您想以編程方式執行此操作,請參閱:
使用C#從FTP服務器下載名稱包含特殊字符的文件
在 PowerShell 中,它會是這樣的:
Add-Type -AssemblyName System.Web
$fileUrl = "https://example.com/path/" + [System.Web.HttpUtility]::UrlEncode($filename)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.