[英]How to download files that contain a pound/hash sign '#' in the filename from an FTP server using PowerShell's FtpWebRequest class
I have built a script for downloading files from an FTP server.我已经构建了一个用于从 FTP 服务器下载文件的脚本。 The script works with all files I have attempted to download except files that contain a
#
.该脚本适用于我尝试下载的所有文件,但包含
#
文件除外。 After doing some research I am unable to find a solution to this problem.在做了一些研究之后,我无法找到解决这个问题的方法。 My code for downloading a file is listed below.
下面列出了我下载文件的代码。
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)"
}
}
I have tried using WebRequest.DownloadFile()
instead and it still does not work with files that contain a #
, I have also tried renaming the file using the FtpWebRequest
rename method and that also did not work.我尝试使用
WebRequest.DownloadFile()
代替,但它仍然不适用于包含#
文件,我也尝试使用FtpWebRequest
重命名方法重命名文件,但也不起作用。
Does anyone know of any solution or workaround to this problem?有谁知道这个问题的任何解决方案或解决方法?
You have to URL-encode the #
as %23
in your URL ( $fileUrl
).您必须在 URL (
$fileUrl
) 中将#
编码为%23
。
If you want to do it programatically, see:如果您想以编程方式执行此操作,请参阅:
Download a file with name including special characters from FTP server in C#使用C#从FTP服务器下载名称包含特殊字符的文件
In PowerShell it would be like this:在 PowerShell 中,它会是这样的:
Add-Type -AssemblyName System.Web
$fileUrl = "https://example.com/path/" + [System.Web.HttpUtility]::UrlEncode($filename)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.