编程语言
首页 > 编程语言> > c# – 密码中的FTP特殊字符?

c# – 密码中的FTP特殊字符?

作者:互联网

我正在尝试登录到ftp服务器.在C#中使用以下代码.

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp-server");

request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
// This example assumes the FTP site uses anonymous logon.
//request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequired;
request.Credentials = new NetworkCredential("userName", "password!#£");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();

但是,当密码包含一些特殊字符时,登录失败.例如(‘!’或’£’)?我得到以下异常.

Unhandled Exception: System.Net.WebException: The remote server returned an error: (530) Not logged in.
  at System.Net.FtpWebRequest.SyncRequestCallback(Object obj)
  at System.Net.FtpWebRequest.RequestCallback(Object obj)
  at System.Net.CommandStream.Dispose(Boolean disposing)
  at System.IO.Stream.Close()
  at System.IO.Stream.Dispose()
  at System.Net.ConnectionPool.Destroy(PooledStream pooledStream)
  at System.Net.ConnectionPool.PutConnection(PooledStream pooledStream, Object owningObject, Int32 creationTimeout, Bo
ean canReuse)
  at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage)
  at System.Net.FtpWebRequest.GetResponse()
  at FtpClientTest.Program.FtpWebRequest() 

密码不包含任何特殊字符时,我不会收到任何异常.

解决方法:

什么是ftp服务器?你能用其他程序登录吗?如果是,请使用wireshark比较电线上的内容.

所以它可能只是ANSI编码,所以试试吧

var secureString = new SecureString();
foreach (var b in Encoding.Default.GetBytes("password!#£"))
    secureString.AppendChar((char)b);

request.Credentials = new NetworkCredential("userName", secureString);

标签:c,net,ftp,ftpwebresponse
来源: https://codeday.me/bug/20190709/1417461.html