当我尝试使用VS2008作为调试器从C#代码FTP到我的Win 2008服务器时,我一直遇到异常.
我的测试类看起来像这样:
public class FTP
{
private string ftpServerIP = "192.168.10.35:21";
private string ftpUserID = "Administrator";
private string ftpPassword = "XXXXXXXX";
private string uploadToFolder = "uploadtest";
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + uploadToFolder + "/" + 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)
{
throw new Exception(ex.Message);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我执行代码时,我在GetRequestStream()调用中遇到FTP错误227的连接失败.在异常中我可以看到连接失败:192.168.10.35:52184
我不知道如何使用端口52184.我在ftpServerIP中指定它应该是端口21.
我在谷歌上发现了一些有相同问题的人,但我还没有找到一个关于如何解决这个问题的好例子,我仍然不明白为什么会这样.
谁知道如何处理这个问题?
更新:
我试图连接到一个不同的FTP帐户,它一切正常.因此我测试了我的192.168.10.35:21 FTP,但它在CuteFTP Pro和其他类似的工作正常.这让它变得更奇怪..
我的猜测是Windows防火墙问题,FTP使用的不仅仅是端口21的其他端口 - 有时将FTP模式从主动更改为被动有助于使事情正常工作.
reqFTP.UsePassive = false;
Run Code Online (Sandbox Code Playgroud)
看看这篇关于FTP的好文章:主动FTP与被动FTP,一个明确的解释