gpt4 book ai didi

.net - 如何使用PowerShell的FtpWebRequest类从FTP服务器下载文件名中包含井号/哈希符号 '#'的文件

转载 作者:行者123 更新时间:2023-12-02 23:17:29 26 4
gpt4 key购买 nike

我已经建立了一个脚本,用于从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(#)中将%23作为$fileUrl进行URL-encode

如果要以编程方式执行此操作,请参见:
Download a file with name including special characters from FTP server in C#

在PowerShell中,它是这样的:

Add-Type -AssemblyName System.Web
$fileUrl = "https://example.com/path/" + [System.Web.HttpUtility]::UrlEncode($filename)

关于.net - 如何使用PowerShell的FtpWebRequest类从FTP服务器下载文件名中包含井号/哈希符号 '#'的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60857034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com