如何使用 PowerShell 的 FtpWebRequest 类从 FTP 服务器下载文件名中包含井号/井号“#”的文件

问题描述 投票:0回答:1

我已经构建了一个用于从 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
重命名方法重命名文件,但这也不起作用。

有谁知道这个问题的任何解决方案或解决方法吗?

.net powershell ftp ftpwebrequest
1个回答
3
投票

您必须将 #

URL 编码
为 URL 中的
%23
(
$fileUrl
)。


如果您想以编程方式执行此操作,请参阅:
用 C# 从 FTP 服务器下载名称包含特殊字符的文件

在 PowerShell 中它会是这样的:

Add-Type -AssemblyName System.Web

$fileUrl =
    "https://example.com/path/" +
    [System.Web.HttpUtility]::UrlEncode($filename)
© www.soinside.com 2019 - 2024. All rights reserved.