在C#中使用FtpWebRequest时设置端口号 [英] Set Port number when using FtpWebRequest in C#
问题描述
当我尝试使用VS2008作为调试器从C#代码通过FTP传输到Win 2008 Server时,总是出现异常.
I keep getting a exception when I try to FTP to my Win 2008 Server from C# code using VS2008 as debugger.
我的测试类如下:
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);
}
}
}
当我执行代码时,在GetRequestStream()调用中收到FTP错误227的连接失败.在例外情况下,我可以看到连接失败:192.168.10.35:52184
When I execute the code I get a Connection Failed with FTP error 227 in the GetRequestStream() call. In the exception I can see the connection fails to: 192.168.10.35:52184
我不知道端口52184是如何产生的.我在ftpServerIP中指定应为端口21.
I have no idea how it comes up with port 52184. I specify in the ftpServerIP that it should be port 21.
我在Google上发现了一些存在相同问题的人,但是我没有找到解决该问题的好例子,我仍然不明白为什么会发生这种情况.
I have found a few persons with the same issues on google but I haven't found a good example on how this is solved and I still don't understand why it happens.
任何人都知道如何处理此问题?
Anyone know how to handle this issue??
更新:
我尝试连接到其他FTP帐户,并且一切正常.因此,我测试了我的192.168.10.35:21 FTP,但在CuteFTP Pro之类的系统中工作正常.这只会使它更加奇怪..
I have tried to connect to a different FTP account and there it all works fine. Therefore I tested my 192.168.10.35:21 FTP but it works fine in CuteFTP Pro and the likes. This just makes it even more strange..
推荐答案
我的猜测是Windows防火墙问题,FTP使用的端口不只是端口21,有时将FTP模式从主动模式更改为被动模式有助于使工作正常./p>
My guess would be Windows firewall issues, FTP uses other ports than just port 21 - sometimes changing the FTP mode from active to passive helps to get things working.
reqFTP.UsePassive = false;
请参阅有关FTP的这篇好文章:主动FTP与被动FTP的明确解释
Look at this good article on FTP: Active FTP vs. Passive FTP, a Definitive Explanation
这篇关于在C#中使用FtpWebRequest时设置端口号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!