从ftp指定目录下载文件的C#代码

/// <summary>
        /// Provides the filePath and fileName
        /// </summary>
        /// <param name="filePath">the path of the file.</param>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="errorinfo">the error info.</param>
        /// <returns>If this method succeeds, it returns true. Otherwise, it returns an error code and false.</returns>
        public bool DownloadFile(string filePath, string fileName, out string errorinfo)
        {
            string onlyFileName = Path.GetFileName(fileName);
            string newFileName = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + onlyFileName;
            Log.WriteUserLog(newFileName, 0, 0, 0);
            errorinfo = string.Empty;

            if (File.Exists(newFileName))
            {
                //errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);
                return false;
            }

            try
            {
                string url = "ftp://" + ftpServerIP + "/" + fileName;
                Connect(url);//连接

                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                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);
                FileStream outputStream = new FileStream(newFileName, FileMode.Create);

                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();
                outputStream.Close();
                response.Close();
                errorinfo = "";
                return true;
            }
            catch (Exception ex)
            {
                errorinfo = string.Format("因{0},无法下载", ex.Message);
                return false;
            }
        }

 

你可能感兴趣的