我想使用 FTP 上传和下载文件。我设法为我的上传和下载方法整理了以下代码。我被困在同一个地方。
如果我使用:
ftpRequest.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponseStream();
它给了我 500 错误。但是,如果我只使用:
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponseStream();
我得到:远程服务器返回错误:227 进入被动模式。
这在下载和上传方法中是相同的行为。我可以使用在线客户端上传文件,所以我知道服务器设置得很好。我按照某些线程的建议禁用了防病毒软件的防火墙,但这也不起作用。现在我不知道该怎么办。我的上传和下载方法如下:
我的上传方法
private static void Upload ()
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://ftp.myserver.com/");
ftpRequest.Credentials = new NetworkCredential("username", "password");
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
ftpRequest.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
Console.WriteLine(line);
line = streamReader.ReadLine();
}
streamReader.Close();
}
我的下载方法
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(@"C:\download.csv", FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://ftp.myserver.com/upload/myfile.csv"));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.UsePassive = false;
reqFTP.KeepAlive = true;
reqFTP.Credentials = new NetworkCredential("username", "password");
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
}