1

我是 FTP 的新手。我正在尝试使用 StreamWriter 在 FTP 中写入文件。写入文件后,我不想关闭流,因为我有一些工作需要完成。大约 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();
        }
    }
4

1 回答 1

0

您必须将 timout 设置为无穷大,-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");
于 2013-05-30T10:04:40.493 回答