我想写一个程序,它将从FTP下载几个文件,将它们压缩后再上传到同一个FTP位置。FTP下载/上传错误504
我已经试图下载一个文件。如果失败,它会再试一次。
如果没有错误发生,所有文件下载并上传文件。
如果在下载时发生任何错误,它会在重新尝试时下载它们,但是无法上传。
我认为问题归咎于没有正确关闭连接,但我不能为我的生活弄清楚。
这是我的代码;我已经添加它失败:
上传:
FileInfo fileInf = new FileInfo("directory" + zip + ".zip");
string uri = "ftp://address" + fileInf.Name;
FtpWebRequest reqFTP2;
reqFTP2 = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://address" + fileInf.Name));
reqFTP2.Credentials = new NetworkCredential("username", "password");
reqFTP2.KeepAlive = true;
reqFTP2.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP2.UseBinary = true;
reqFTP2.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP2.GetRequestStream(); //FAILS HERE
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)
{
}
下载:
int errorOccured = 0;
while (errorOccured < 1)
{
FileStream outputStream = new FileStream("directory\\" + file, FileMode.Create);
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://address/" + file));
reqFTP.Credentials = new NetworkCredential("username", "password");
try
{
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
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();
errorOccured++;
}
catch (Exception er)
{
outputStream.Close();
}
你得到了什么特定的例外? –
System.Net.WebException:远程服务器返回错误:(503)错误的命令序列。 在System.Net.FtpWebRequest.SyncRequestCallback(对象OBJ) 在System.Net.FtpWebRequest.RequestCallback(对象OBJ) 在System.Net.CommandStream.InvokeRequestCallback(对象OBJ) 在System.Net.CommandStream.Abort(例外e) at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage) at System.Net.FtpWebRequest.GetRequestStream() at RightMove.Form1.uploadFTP(String zip)in C:\ Users \ dir \ Form1.cs:line 407 – BenG