我是FTP的新手。我正在尝试使用StreamWriter.Fnce写入文件中的文件。写入文件后,我不想关闭流,因为我有一些必须完成的工作。后来大约1小时,如果我尝试使用相同的streamWriter写,我得到上述错误。 以下是我的代码段
public void WriteToFTP()
{
bool isConnectionEstablished = false;
StreamWriter stream = null;
try
{
for (int i = 1; i < 5; i++)
{
string message = string.Format("File - {0}.", i.ToString());
if (!isConnectionEstablished)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("My FTP path"));
request.Credentials = new NetworkCredential("asdf", "asdf@123");
request.Proxy = null;
request.UseBinary = true;
request.ConnectionGroupName = string.Empty;
request.UsePassive = true;
request.EnableSsl = false;
isConnectionEstablished = true;
stream = new StreamWriter(request.GetRequestStream()) { AutoFlush = true };
}
stream.WriteLine(message);//Here i am getting the error for the i = 2(after doing my work)
//Doing work which may take more than 1 hour.
}
}
catch (Exception exe)
{
//The Error "Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host" is being caught here.
}
finally
{
if (stream != null)
stream.Close();
}
}
答案 0 :(得分:0)
必须将超时设置为无穷大,-1是无穷大的值,请参阅此示例:
FtpWebRequest reqFTP;
string fileName = @"c:\downloadDir\localFileName.txt";
FileInfo downloadFile = new FileInfo(fileName);
string uri = "ftp://ftp.myftpsite.com/ftpDir/remoteFileName.txt";
FileStream outputStream = new FileStream(fileName, FileMode.Append);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Timeout = -1;
reqFTP.UsePassive = 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);
Console.WriteLine("Connected: Downloading File");
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
Console.WriteLine(readCount.ToString());
}
ftpStream.Close();
outputStream.Close();
response.Close();
Console.WriteLine("Downloading Complete");