【问题标题】:The remote server returned an error: (421) Service not available, closing control connection远程服务器返回错误:(421)服务不可用,关闭控制连接
【发布时间】:2014-03-05 22:51:56
【问题描述】:

我正在为大量文件运行此代码以通过 ftp 在本地传输到另一台服务器。问题是我定期收到错误远程服务器返回错误:(421)服务不可用,正在关闭控制连接。代码是否有问题,传输文件的更好方法更快更有效。所有文件都需要传输,所以我在考虑一个while循环并捕获错误,直到文件夹中的所有文件都已传输。这是我收到的周期性错误:

foreach (FileInfo file in files)
{
    try
    {
        // Get the object used to communicate with the server.
        FtpWebRequest request =
            (FtpWebRequest)
                WebRequest.Create(String.Format("{0}{1}/{2}", Host, destinationPath,
                    file.Name));
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.KeepAlive = false;
        /* 20 mins timeout */
        request.Timeout = 1200000;
        request.ReadWriteTimeout = 1200000;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential(Username, Password);

        // Copy the contents of the file to the request stream.
        byte[] fileContents = File.ReadAllBytes(file.FullName);

        request.ContentLength = fileContents.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(fileContents, 0, fileContents.Length);
        }

        //using (FtpWebResponse response = (FtpWebResponse) request.GetResponse())
        //{

        //}

        if (deleteSourcePath)
        {
            File.Delete(file.FullName);
        }
    }
    catch (Exception ex)
    {
        //  Log.Warn("Error Moving Images", ex.Message);
    }
}

【问题讨论】:

  • 似乎可以通过吃异常的catch语句的数量来判断一段代码sn-p的好坏。

标签: c# ftp


【解决方案1】:

在 FtpWebResponse 对象上调用 Close。这将释放关联的端口。

FtpWebResponse response = (FtpWebResponse) request.GetResponse();
// ...
finally
{
    if (response != null)
    {
        response.Close();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2023-03-25
    • 2014-09-08
    相关资源
    最近更新 更多