此方法无效,正在解决
借用了别人的c#代码做ftp,发现该ftp传输文件时不能下载带有中文名的文件。服务器是linux服务器不识别中文,客户端是win8。
这种问题是由客户端中文编码与服务器编码不一致造成的,要么让服务器识别中文编码,要么让客户端“聪明”些改变下载策略。
本人尝试前者数次,奈何水平不够,至今未能修改linux系统语言,只好尝试后者。
修改前该ftp调用方法如下:
FtpWeb ftp = new FtpWeb("115.77.365.99","/var/ftp/test1","test1","553569");
ftp.Download("d:", @"1.txt");
即可将文件"1.txt" 从服务器的/var/ftp/test1目录下下载至本地的"d:"目录下
然而在服务器上将“1.txt”改为"去.txt"之后就不能下载了,在服务器上文件名显示为“??.txt”
本人最终使用了两条语句来解决这个问题:
public static string z百分号变汉字(string aa) //GBK编码转换成汉字,如把"%c8%a5.txt"变成"去.txt" (c8 a5,不一定对应的就是“去”这个字,记不清//了)
{
return aa= System.Web.HttpUtility.UrlDecode(aa, System.Text.Encoding.GetEncoding("GB2312"));
}
public static string z汉字变百分号(string aa) //汉字变成“%c8%a5.txt”这种类型
{
return aa = System.Web.HttpUtility.UrlEncode(aa, Encoding.GetEncoding("GBK"));
}
具体的原理也不甚清楚,求解释,全部代码及调用方式如下(借用的别人的程序,版权不是俺的,俺也不清楚哪里是最早的出处):
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Globalization;
using System.Web;
/*
调用方法
FtpWeb ftp = new FtpWeb("333.22.111.22","/var/ftp/test1","test1","553569");
ftp.Download("d:", @"去.txt");
*/
namespace FtpLib
{
public class FtpWeb
{
string ftpServerIP;
string ftpRemotePath;
string ftpUserID;
string ftpPassword;
string ftpURI;
public static string z百分号变汉字(string aa)
{
return aa= System.Web.HttpUtility.UrlDecode(aa, System.Text.Encoding.GetEncoding("GB2312"));
}
public static string z汉字变百分号(string aa)
{
return aa = System.Web.HttpUtility.UrlEncode(aa, Encoding.GetEncoding("GBK"));
}
/// <summary>
/// 连接FTP
/// </summary>
/// <param name="FtpServerIP">FTP连接地址</param>
/// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
/// <param name="FtpUserID">用户名</param>
/// <param name="FtpPassword">密码</param>
public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
{
//修改
FtpRemotePath = z汉字变百分号(FtpRemotePath);
//修改结束
ftpServerIP = FtpServerIP;
ftpRemotePath = FtpRemotePath;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
ftpURI =@"ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
/// <summary>
/// 上传
/// </summary>
/// <param name="filename"></param>
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = ftpURI + fileInf.Name;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex)
{