Reputation: 47
I was trying to write a test script to upload file to FTP. My system is Windows 7. When I use Windows Explorer to watch the FTP, all Chinese are in wrong characters. Using Firefox to watch, in GBK encoding, all files' names are correct. Now I want to upload files in GBK encoding names, so Firefox will see all names right. Here's my attempt:
$coder1= [system.Text.encoding]::GetEncoding('GB2312')
$coder2 = [system.Text.encoding]::UTF8
$user = "test"
$password = "test"
$ftp = 'ftp://10.10.10.253/shzx/'
$souce = '新建文本文档.txt'
$loacalfile = Get-Item w:\test\新建文本文档.txt
$souce1 = [system.Web.HttpUtility]::UrlEncode($souce,$coder1)
$encodeA = $ftp+$souce
$request = [system.Net.FtpWebRequest]::Create($encodeA)
$request = [system.Net.FtpWebRequest]$request
$request.Method=[system.Net.WebRequestMethods+FTP]::uploadfile
$request.Credentials = New-Object system.Net.NetworkCredential($user,$password)
$request.UseBinary = $true
$request.UsePassive = $true
$dest = $request.GetRequestStream()
$src = [system.IO.File]::OpenRead($loacalfile)
$buffsize = [system.Math]::Min($src.length , 4096)
$buff = New-Object system.Byte[] $buffsize
$numbuffloaded = 0
$byteread = 0
do
{
$byteread = $src.read($buff,0,$buffsize)
$dest.write($buff,0,$buffsize)
$numbuffloaded ++
}
while($byteread -ne 0)
$dest.close()
$src.close()
$response = $request.GetResponse()
And after I upload the test file, name is not correct. No matter encode in UTF8 or GBK using Firefox to watch it. I guess FTP server thinks my file name encoding is still UTF-8. So it mistakes decoding. And if I upload with UTF8 encoded name, at least FTP file name will be right when I set Firefox encode in UTF8.
Is there a way to make FTP server decoding right? Should I set FtpWebRequest.Headers
or else?
Upvotes: 2
Views: 633
Reputation: 202514
You cannot choose encoding to be used with FtpWebRequest
.
FtpWebRequest
sends OPTS utf8 on
command to the server, when starting a connection.
If the server responds positively, FtpWebRequest
will use UTF-8. If not, FtpWebRequest
will use local Windows legacy character set.
So all you can do it to set local legacy character set to GB2312
(936
?). Assuming the server responds negatively to OPTS utf8 on
.
Upvotes: 1