gpt4 book ai didi

c# - 在 C# 中使用 FtpWebRequest 时设置端口号

转载 作者:太空狗 更新时间:2023-10-29 17:45:38 25 4
gpt4 key购买 nike

当我尝试使用 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);
}
}
}

当我执行代码时,我在 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;

看看这篇关于 FTP 的好文章:Active FTP vs. Passive FTP, a Definitive Explanation

关于c# - 在 C# 中使用 FtpWebRequest 时设置端口号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/876712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com