C#下载ftp文件时文件名里含有特殊字符的处理方法 100
我创建了一个method来与ftpserver进行交流。现在的问题是uri里面带有特殊字符如“#”,“@”等就无法下载或者上传。只好用蹩脚的方式escape了一下。有没有...
我创建了一个method来与ftp server 进行交流。现在的问题是uri里面带有特殊字符如“#”,“@”等就无法下载或者上传。只好用蹩脚的方式escape了一下。 有没有比较优雅的方式escape特殊字符在uri里?
// Get the request using a specific URI
static public FtpWebRequest GetWebRequest(string method, string uri)
{
Uri serverUri = new Uri(uri);
if (serverUri.ToString().Contains("#"))
{
serverUri = new Uri(serverUri.ToString().Replace("#", Uri.HexEscape('#')));
}
Console.WriteLine(serverUri.ToString());
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return null;
}
try
{
var reqFTP = (FtpWebRequest)FtpWebRequest.Create(serverUri);
reqFTP.Method = method;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(userId, password);
reqFTP.Proxy = null;
reqFTP.KeepAlive = false;
reqFTP.UsePassive = false;
return reqFTP;
}
catch (Exception ex)
{
logWriter.WriteLog("Get Web Request: ", "Cannot connect to " + uri + "\n" + "Error: " + ex.Message);
return null;
}
}
var request = GetWebRequest(WebRequestMethods.Ftp.UploadFile, "ftp://" + ip + @"/" + remoteDir + @"/" + destDir + @"/" + file.Name); 展开
// Get the request using a specific URI
static public FtpWebRequest GetWebRequest(string method, string uri)
{
Uri serverUri = new Uri(uri);
if (serverUri.ToString().Contains("#"))
{
serverUri = new Uri(serverUri.ToString().Replace("#", Uri.HexEscape('#')));
}
Console.WriteLine(serverUri.ToString());
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return null;
}
try
{
var reqFTP = (FtpWebRequest)FtpWebRequest.Create(serverUri);
reqFTP.Method = method;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(userId, password);
reqFTP.Proxy = null;
reqFTP.KeepAlive = false;
reqFTP.UsePassive = false;
return reqFTP;
}
catch (Exception ex)
{
logWriter.WriteLog("Get Web Request: ", "Cannot connect to " + uri + "\n" + "Error: " + ex.Message);
return null;
}
}
var request = GetWebRequest(WebRequestMethods.Ftp.UploadFile, "ftp://" + ip + @"/" + remoteDir + @"/" + destDir + @"/" + file.Name); 展开
2个回答
2013-07-24
展开全部
So it is probably just ANSI encoding, so try
var secureString = new SecureString();
foreach (var b in Encoding.Default.GetBytes("C# test's file"))
secureString.AppendChar((char)b);
var stringResult = string.Empty;
IntPtr bstr = Marshal.SecureStringToBSTR(secureString);
try
{
stringResult =Marshal.PtrToStringBSTR(bstr);
}
finally
{
Marshal.FreeBSTR(bstr);
}
return stringResult;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询