跳到主要內容

[C#] FTP download sample code


If you'd like DL file through WebRequestMethods, maybe you could try below sample code

Input:
filePath = "ftp://100.251.237.125/update.xml"
targetPath = update.xml


public bool DwonlaodFileFromFTP(string filePath, string targetPath, out string errorMessage)
        {
            // initialize
        
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(filePath);
            request.Credentials = new NetworkCredential(_user, _password);
            request.Proxy = null;
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.UsePassive = false;
           
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
             
            using (Stream fileWriter = File.Create(targetPath))
            {
                responseStream.CopyTo(fileWriter);
                if (fileWriter.ReadByte() == 0)
                {
                    fileWriter.Close();
                    return false;
                }
               
            }
            response.Close();
            return true;
        }


留言