【问题标题】:FTP request to server can not connect remote server对服务器的 FTP 请求无法连接远程服务器
【发布时间】:2012-09-21 14:55:02
【问题描述】:

我在这里找到了许多类似的文章,但仍然无法解决我的问题。 我正在尝试将文本文件上传到 ftp 服务器。我使用了多种方法,所有方法都出现相同的错误:“无法连接到远程服务器”

方法1: filename 是文件所在的完整路径

    private string Upload(string ftpServer, string userName, string password, string filename)
    {
        string reply = "Success";
        try
        {
            using (System.Net.WebClient client = new System.Net.WebClient()) //System.Net.WebClient client = new System.Net.WebClient()
            {
                client.Credentials = new System.Net.NetworkCredential(userName, password);
                client.Proxy = new WebProxy();
                FileInfo fi = new FileInfo(filename);
                client.UploadFile(ftpServer + "//" + fi.Name, "STOR", filename);
            }
        }
        catch (Exception ex)
        {
            reply = ex.Message;
        }
        return reply;
}

方法二:

文件名 = "D:\文件夹\file.txt" 公共静态无效uploadFileUsingFTP(字符串文件名) { FileInfo fileInf = new FileInfo(filename); string uri = "ftp://" + serverIP + "/" + fileInf.Name;

            FtpWebRequest reqFTP; 
            // Create FtpWebRequest object from the Uri provided
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            reqFTP.Proxy = null;
            // Provide the WebPermission Credintials
            reqFTP.Credentials = new NetworkCredential(user, pass); 

            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            reqFTP.KeepAlive = false; 

            // Specify the command to be executed.
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile; 

            // Specify the data transfer type.
            reqFTP.UseBinary = true; 

            // Notify the server about the size of the uploaded file
            FileStream fs = File.OpenRead(filename); 
            reqFTP.ContentLength = fileInf.Length; 
            // The buffer size is set to 2kb
            int buffLength = Convert.ToInt32(fs.Length);
            byte[] buff = new byte[buffLength];
            int contentLen; 

            try
            {
                // Stream to which the file to be upload is written
                Stream strm = reqFTP.GetRequestStream(); 

                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength); 

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                } 

                // Close the file stream and the Request Stream
                strm.Close();
                fs.Close();
            }

            catch (Exception ex)
            {
                string s = ex.Message;
            }

        }

方法3:

 public static void Sample(string filename)
        {

            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://serverip/"); //test.htm
            request.Method = WebRequestMethods.Ftp.UploadFile;

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

            try
            {
                // Copy the contents of the file to the request stream.
                StreamReader sourceStream = new StreamReader(filename);
                byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();
                request.ContentLength = fileContents.Length;

                request.Proxy = null;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

                response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadLine();

        }

使用它们中的每一个都会导致相同的问题,是的,我可以使用 filezilla 连接到 ftp 并传输文件。

我知道我一定错过了一些非常愚蠢的东西,但这花了我很多时间。 任何建议都会受到重视。

【问题讨论】:

    标签: c# ftp


    【解决方案1】:

    连接问题可能很麻烦。像WireShark 这样的工具可以帮助追踪问题,例如尝试主动与被动模式 FTP 传输时。

    我一直在使用以下代码,效果很好:

            bool result = false;
            long length = 0;
            // Set up the FTP upload.
            //   The URI for the request specifies the protocol, the server and the filename.
            FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerUrl + "/" + targetFilename);
            ftpRequest.EnableSsl = false;
            ftpRequest.KeepAlive = true;
            ftpRequest.ReadWriteTimeout = ftpTimeout; // To perform an individual read or write.
            ftpRequest.Timeout = ftpTimeout; // To establish a connection or start an operation.
            ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
    
            // Upload the file.
            using (FileStream fileStream = File.OpenRead(filename))
            {
                using (Stream ftpStream = ftpRequest.GetRequestStream())
                {
                    fileStream.CopyTo(ftpStream);
                    length = fileStream.Length;
                    ftpStream.Close();
                }
                FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                if (ftpResponse.StatusCode == FtpStatusCode.ClosingData)
                    result = true;
                else
                    throw new Exception(ftpResponse.StatusDescription + " (" + ftpResponse.StatusCode + ")");
                ftpResponse.Close();
            }
    

    【讨论】:

      【解决方案2】:

      已经在另一个帖子中回复过,但在这里也重复了。我遇到了同样的问题,这是我的解决方案。

      request.Credentials = new NetworkCredential(
          usernameVariable.Normalize(),passwordVariable.Normalize(),domainVariable.Normalize());
      

      详情可见here

      希望它对某人有所帮助。

      【讨论】:

        【解决方案3】:

        在您的web.config 中添加以下内容,让您的 FtpWebRequest 使用默认代理

        <defaultProxy enabled="true" useDefaultCredentials="true">
        </defaultProxy>
        

        【讨论】: