【发布时间】:2011-10-28 19:49:41
【问题描述】:
我正在尝试编写一个程序,该程序将从 FTP 下载一些文件,将它们压缩,然后再次将它们上传到相同的 FTP 位置。
我已经让它尝试下载文件。如果失败,它会再试一次。
如果没有错误发生,所有文件下载并上传文件。
如果下载时出现任何错误,它会在重新尝试时下载它们,但上传失败。
我认为问题归结为未正确关闭连接,但我终其一生都无法弄清楚。
这是我的代码;我已经添加了失败的地方:
上传:
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(Object obj) 在 System.Net.FtpWebRequest.RequestCallback(Object obj) 在 System.Net.CommandStream.InvokeRequestCallback(Object obj) 在 System.Net.CommandStream.Abort(Exception e) 在 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
标签: c# file-upload ftp download