[这是我编写的从FTP服务器下载文件的功能。当我在桌面应用程序或控制台应用程序上调用它时,此方法有效。但是失败,并且在Windows Service中提供此错误消息或给出从Windows Scheduler调用的控制台应用程序时给出错误消息。我需要每天获取选定的文件。我正在尝试实现自动化,而不是每天早晨手动运行。
private void GetFile(string url, string user, string pwd, string folder, string filename
, string destloc, string destfile)
{
try
{
string RemoteFtpPath = url + folder + "/" + filename;
String DestLoc = destloc + destfile;
String Username = user;
String Password = pwd;
Boolean UseBinary = false; // use true for .zip file or false for a text file
Boolean UsePassive = false;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(RemoteFtpPath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.KeepAlive = true;
request.UsePassive = UsePassive;
request.UseBinary = UseBinary;
request.Credentials = new NetworkCredential(Username, Password);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
if (File.Exists(DestLoc))
File.Delete(DestLoc);
using (FileStream writer = new FileStream(DestLoc, FileMode.Create))
{
long length = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[2048];
readCount = responseStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
writer.Write(buffer, 0, readCount);
readCount = responseStream.Read(buffer, 0, bufferSize);
}
}
reader.Close();
response.Close();
}
catch (Exception ex)
{
throw ex;
}
}
通过更改属性解决了该问题。
request.KeepAlive = false;
request.UsePassive = true;
request.UseBinary = false;