现在有一个任务 每天从ftp上取一个数据 ,下来处理后再上传到ftp上。我想做一个计划任务,每天8点自动处理操作。
现在问题是怎么用程序实现ftp上传下载的功能呢
(ftp账号密码是知道的)

解决方案 »

  1.   

    class Program
        {
            //連接ftp服務器的IP or DNS地址
            private static string ftpServerIP = Properties.Settings.Default.ftpServerIP;
            //連接ftp服務器的UserID
            private static string ftpUserID = Properties.Settings.Default.ftpUserID;
            //連接ftp服務器的password
            private static string ftpPassword = Properties.Settings.Default.ftpPassword;
            //設定下載檔案到指向的目的路徑(絕對路徑)
            private static string localFolder = Path.GetFullPath("DownLoadFolder/");
            //文件傳輸協議(FTP)的客戶端對象
            static FtpWebRequest reqFTP;
            private static string fileServerPath = "ftp://" + ftpServerIP + "/" + "PosSales/";
            //mail相關訊息
            private static string _job_Message = "";
            private static string _job_Err_Message = "";
            /// <summary>
            /// 程序入口
            /// </summary>
            /// <param name="args"></param>
            static void Main(string[] args)
            {
                GetFileList(fileServerPath, WebRequestMethods.Ftp.ListDirectory);
                WriteDataToSalesTable();
                SendMailFromJob();
            }        /// <summary>
            /// 公用:連接ftp服務器
            /// </summary>
            /// <param name="path"></param>
            private static void ConnectFtpServer(string path)
            {
                // 根据uri创建FtpWebRequest对象
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));            //指定要求完成後,與ftp服務器的控制連接是否關閉
                reqFTP.KeepAlive = false;            //指定数据传输类型
                reqFTP.UseBinary = true;            //ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            }        /// <summary>
            /// 1.从ftp服务器的指定目錄下获得文件列表
            /// </summary>
            /// <param name="path">ftp服務器IP(DNS)地址</param>
            /// <param name="WRMethods">對ftp服務器上的目錄或文檔的操作方式</param>
            /// <returns></returns>
            private static void GetFileList(string path,string WRMethods)
            {
                string[] downloadFiles;
                WebResponse response = null;
                StreamReader reader = null;
                StringBuilder result = new StringBuilder();
                string dateStr = DateTime.Now.ToString("yyyyMMdd");
                dateStr = "20110224";
                try 
                {
                    //連接ftp服務器
                    ConnectFtpServer(path);
                    //設定要傳送到ftp服務器的命令
                    reqFTP.Method = WRMethods;
                    //傳回ftp服務器回應
                    response = reqFTP.GetResponse();
                    reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                    string line = reader.ReadLine();
                    while(line != null)
                    {
                        //判斷文件全名是否為已日期格式開頭和.txt格式結尾
                        if ((line.Length >= 18) && (line.Substring(0, 8) == dateStr) && (line.Substring(line.LastIndexOf('.')+1,3) == "txt"))
                        {
                            result.Append(line);
                            result.Append("\n");
                        }
                        line = reader.ReadLine();
                    }
                    if (string.IsNullOrEmpty(result.ToString()) == true || result.ToString().Length <= 0)
                    {
                        _job_Err_Message += "<BR><BR>2.本次未獲取到FTP遠端主機上銷售資料檔!";
                    }
                    else
                    {
                        // to remove the trailing '\n'
                        result.Remove(result.ToString().LastIndexOf('\n'), 1);
                        downloadFiles = result.ToString().Split('\n');
                        if (downloadFiles.Length > 0)
                        {
                            DownLoad(localFolder, downloadFiles);
                        }
                        reader.Close();
                        response.Close();
                        //****************************
                        _job_Message += "<BR><BR>1.本次讀取到的文件列表為:" + result;
                    }
                }
                catch (Exception ex)
                {
                    _job_Err_Message += "<BR><BR>3.从FTP遠端主機的根目錄下获得文件列表時發生的錯誤訊息:<FONT COLOR='RED'>" + ex.Message.ToString()+"</FONT>";
                    downloadFiles = null;
                }
            }        /// <summary>
            /// 2.根據傳入的文檔名稱从ftp服务器的特定目錄下载文件
            /// </summary>
            /// <param name="filePath">本地路徑</param>
            /// <param name="fileNames">ftp服務器上的文檔名稱</param>
            /// <param name="errorInfo">錯誤訊息</param>
            /// <returns></returns>
            private static void DownLoad(string filePath,string []fileNames)
            {
                string errorInfo = "";
                try
                {
                    for (int i = 0; i < fileNames.Length;i++ )
                    {
                        string onlyFileName = Path.GetFileName(fileNames[i]);
                        string newFileName = filePath + onlyFileName;
                        string dateStr = DateTime.Now.ToString("yyyyMMdd");
                        //ftp上的銷售資料是在執行這個job的前一天夜晚同步上去的。(上傳到ftp服務器上的文件名是上傳的時間)
                        dateStr = "20110224";//手動執行此job時使用,會覆蓋使用上面那行的日期
                        //判斷文件全名是否為已日期格式開頭和.txt格式結尾
                        if(fileNames[i].Substring(0,8) != dateStr)
                        {
                            continue;
                        }
                        if(Path.GetExtension(newFileName) != ".txt")
                        {
                            continue;
                        }
                        if(File.Exists(newFileName))
                        {
                            errorInfo = string.Format("本地文件{0}已存在,无法下载!", newFileName);
                        }
                        string url = fileServerPath + fileNames[i];
                        ConnectFtpServer(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 = "";
                    }
                }
                catch(Exception ex)
                {
                    errorInfo += ex.Message.ToString();
                    _job_Err_Message += "<BR><BR>4.从FTP遠端主機指定目錄下载文件時發生的錯誤訊息:<FONT COLOR='RED'>"+ errorInfo +"</FONT>";
                }
            }
      

  2.   

    上面是我前阵子写的一个通过测试的从ftp主机下载文件的实例下载的话,也是同理,只需要稍微改改就好了希望对楼主有帮助
      

  3.   

    谢谢sfxdawn
     我试一哈啊
      

  4.   

    我这里面的需求是不知道文件的具体名称的情况下,才不得已去读某个文件夹下面的所有文件列表最后筛选出后缀名为.txt文件,下载到本机指定的目录如果你事先知道了文件名已经该文件在FTP主机上的目录,还更加简单一点了哈WebRequestMethods.Ftp.ListDirectory 有好几个枚举选项呢
      

  5.   

    我是通过代理服务器上网的,所以加入了代理设置,不需要的把IsProxy设置成false,设置其他需要的属性就能下载了,文件大小拿response报头
    namespace ChintFtp
    {
        /// <summary>
        /// Create By 温州-小李
        /// 7.21
        /// </summary>
        public partial class FtpClient : Component
        {        #region 构造函数        public FtpClient()
            {
                InitializeComponent();
            }        public FtpClient(IContainer container)
            {
                container.Add(this);            InitializeComponent();
            }        #endregion        #region 私有变量
            //属性变量
            private NetworkCredential _Credential = new NetworkCredential();
            private Uri _HttpPath = null;
            private bool _IsProxy = false;
            private bool _IsAsync = true;
            private string _FileName;
            private string _ProxyAddress;
            //内部变量
            private FileStream fs;
            Stream stream;
            private bool IsHasExit = false;
            #endregion        #region 事件与委托        /// <summary>
            /// 连接状况
            /// </summary>
            public delegate void FtpConnectStateEventHandler(object sender, EventArgs e);
            /// <summary>
            /// 连接状态发生变化时引发事件
            /// </summary>
            public event FtpConnectStateEventHandler FtpConnectStateEvent;
            /// <summary>
            /// 捕获异常
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            public delegate void FtpErrorEventHandler(object sender, EventArgs e);
            /// <summary>
            /// 下载时引发的异常
            /// </summary>
            public event FtpErrorEventHandler FtpErrorEvent;        #endregion        #region 记录下载情况        private string[] DownLoadStatus = new string[3];        #endregion        #region 定义缓冲区        private byte[] buffer = new byte[1024];        /// <summary>
            /// 设置和获取缓冲区大小
            /// </summary>
            [Browsable(true),
            Category("Http"),
            Description("设置和获取缓冲区大小")]
            public int ReadByteCount
            {
                get
                {
                    return buffer.Length;
                }
                set
                {
                    buffer = new byte[value];
                }
            }        #endregion        #region 成员属性        /// <summary>
            /// 代理用户认证
            /// </summary>
            [Browsable(false),
            DefaultValue(false)]
            public NetworkCredential Credential
            {
                get
                {
                    return _Credential;
                }
                set
                {
                    if (value != null&&
                        !string.IsNullOrEmpty(value.Domain))
                    {
                        _Credential = value;
                        _IsProxy = true;
                    }
                }
            }        /// <summary>
            /// 用户名
            /// </summary>
            [Browsable(true),
            Category("Proxy"),
            DefaultValue(false),
            Description("代理用户名")]
            public string CredentialUserName
            {
                get
                {
                    if (_Credential != null)
                        return _Credential.UserName;
                    return null;
                }
                set
                {
                    if (_Credential != null &&
                        !string.IsNullOrEmpty(value))
                    {
                        _Credential.UserName = value;
                        _IsProxy = true;
                    }
                }
            }        /// <summary>
            /// 代理域名
            /// </summary>
            [Browsable(true),
            Category("Proxy"),
            DefaultValue(false),
            Description("代理域名")]
            public string CredentialDomain
            {
                get
                {
                    if (_Credential != null)
                        return _Credential.Domain;
                    return null;
                }
                set
                {
                    if (_Credential != null &&
                        !string.IsNullOrEmpty(value))
                    {
                        _Credential.Domain = value;
                        _IsProxy = true;
                    }
                }
            }        /// <summary>
            /// 代理密码
            /// </summary>
            [Browsable(true),
            Category("Proxy"),
            PasswordPropertyText(true),
            Description("代理密码")]
            public string CredentialPassword
            {
                get
                {
                    if (_Credential != null)
                        return _Credential.Password;
                    return null;
                }
                set
                {
                    if (_Credential != null &&
                        !string.IsNullOrEmpty(value))
                    {
                        _Credential.Password = value;
                        _IsProxy = true;
                    }
                }
            }        /// <summary>
            /// 代理服务地址
            /// </summary>
            [Browsable(true),
            Category("Proxy"),
            DefaultValue(false),
            Description("代理服务地址")]
            public string ProxyAddress
            {
                get
                {
                    return _ProxyAddress;
                }
                set
                {
                    if (!_IsProxy)
                        return;
                    IPAddress ip;
                    if (IPAddress.TryParse(value, out ip))
                    {
                        _ProxyAddress = ip.ToString();
                    }
                    else
                    {
                        throw new Exception("代理服务地址错误");
                    }
                }
            }        /// <summary>
            /// 下载地址
            /// </summary>
            [Browsable(true),
            Category("Http"),
            DefaultValue(false),
            Description("下载地址")]
            public string HttpPath
            {
                get
                {
                    if (_HttpPath != null)
                        return _HttpPath.AbsoluteUri;
                    return null;
                }
                set
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(value))
                            _HttpPath = new Uri(value);                    
                    }
                    catch (Exception ex)
                    {                    
                        _HttpPath = null;
                        throw ex;
                    }
                }
            }        [Browsable(true),
            Category("Http"),
            DefaultValue(false),
            Description("文件保存名字")]
            public string FileName
            {
                get
                {
                    return _FileName;
                }
                set
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        _FileName = value;
                        return;
                    }
                    if (Path.IsPathRooted(value))
                        _FileName = value;
                    else
                        throw new Exception("文件地址错误");
                }
            }        /// <summary>
            /// 是否使用代理
            /// </summary>
            [Browsable(true),
            Category("Proxy"),
            DefaultValue(false),
            Description("是否使用代理")]
            public bool IsProxy
            {
                get
                {
                    return _IsProxy;
                }
                set
                {
                    _IsProxy = value;
                    if (!_IsProxy)
                    {
                        _Credential = new NetworkCredential();
                        _ProxyAddress = null;
                    }
                }
            }        /// <summary>
            /// 是否使用异步
            /// </summary>
            [Browsable(true),
            Category("Http"),
            Description("是否使用异步")]
            public bool IsAsync
            {
                get
                {
                    return _IsAsync;
                }
            }        #endregion
      

  6.   

    接上面代码
          #region 成员方法
            /// <summary>
            /// 获取webRequest
            /// </summary>
            /// <returns></returns>
            public virtual WebRequest GetRequst()
            {
                try
                {
                    WebRequest request = WebRequest.Create(this.HttpPath);
                    WebProxy proxy = this.GetProxy(_IsProxy);
                    request.Proxy = proxy;
                    return request;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            /// <summary>
            /// 获取代理设置
            /// </summary>
            /// <param name="isProxy">是否使用代理</param>
            /// <returns></returns>
            public virtual WebProxy GetProxy(bool isProxy)
            {
                WebProxy proxy;
                if (isProxy)
                {
                    proxy = new WebProxy(_ProxyAddress, true);
                    proxy.Credentials = _Credential;
                }
                else
                {
                    proxy = HttpWebRequest.DefaultWebProxy as WebProxy;
                }
                return proxy;
            }
            /// <summary>
            /// 获取Response
            /// </summary>
            /// <returns></returns>
            public virtual WebResponse GetResponse()
            {
                try
                {
                    WebRequest request = this.GetRequst();
                    return request.GetResponse();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }        /// <summary>
            /// 开始下载,直接到下载完成
            /// </summary>
            public void AsyncDownLoad()
            {
                try
                {                
                    WebRequest request = this.GetRequst();
                    IAsyncResult ar = request.BeginGetResponse(new AsyncCallback(WebAsyncCallBack),
                        request);
                    if (FtpConnectStateEvent != null)
                    {
                        DownLoadStatus[0] = "正在连接站点...";
                        DownLoadStatus[1] = "0";
                        DownLoadStatus[2] = "0";
                        FtpConnectStateEvent(DownLoadStatus, new EventArgs());
                    }
                }
                catch (Exception ex)
                {
                    if (FtpConnectStateEvent != null)
                    {
                        DownLoadStatus[0] = "站点连接失败:" + ex.Message;
                        DownLoadStatus[1] = "0";
                        DownLoadStatus[2] = "0";
                        FtpConnectStateEvent(DownLoadStatus, new EventArgs());
                    }
                }
            }        /// <summary>
            /// AsyncCallBack
            /// </summary>
            /// <param name="ar"></param>
            private void WebAsyncCallBack(IAsyncResult ar)
            {
                try
                {
                    WebRequest request = ar.AsyncState as WebRequest;
                    WebResponse response = request.EndGetResponse(ar);
                    if (response != null)
                    {
                        if (FtpConnectStateEvent != null)
                        {
                            DownLoadStatus[0] = "站点连接成功";
                            DownLoadStatus[1] = "0";
                            DownLoadStatus[2] = "0";
                            FtpConnectStateEvent(DownLoadStatus, new EventArgs());
                        }                    
                        stream = response.GetResponseStream();
                        //提取文件大小
                        DownLoadStatus[2] = GetFileLength(response).ToString();
                        StartDownLoad(stream);  //开始下载
                    }
                    else
                    {
                        if (FtpConnectStateEvent != null)
                        {
                            DownLoadStatus[0] = "站点连接未知名错误";
                            DownLoadStatus[1] = "0";
                            DownLoadStatus[2] = "0";
                            FtpConnectStateEvent(DownLoadStatus, new EventArgs());
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (FtpErrorEvent != null)
                    {
                        FtpErrorEvent(ex.Message, new EventArgs());
                    }
                }
            }        /// <summary>
            /// 开始下载
            /// </summary>
            public void StartDownLoad(Stream stream)
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
                DownLoadStatus[0] = "正在准备下载...";
                DownLoadStatus[1] = "0";
                //DownLoadStatus[2] = stream.Length.ToString();
                if (FtpConnectStateEvent != null)
                {
                    FtpConnectStateEvent(DownLoadStatus, new EventArgs());
                }
                if (File.Exists(this.FileName))
                    File.Delete(this.FileName);
                fs = new FileStream(this._FileName,FileMode.CreateNew,FileAccess.Write);
                stream.BeginRead(buffer, 0, buffer.Length, StreamAsyncCallback, stream);
                DownLoadStatus[0] = "开始下载";
                DownLoadStatus[1] = "0";
                if (FtpConnectStateEvent != null)
                {
                    FtpConnectStateEvent(DownLoadStatus, new EventArgs());
                }
            }
            /// <summary>
            /// 异步读取文件
            /// </summary>
            /// <param name="ar"></param>
            private void StreamAsyncCallback(IAsyncResult ar)
            {
                if (!IsHasExit) //是否要退出,false
                {
                    try
                    {
                        Stream stream = ar.AsyncState as Stream;
                        int i;
                        if (stream != null)
                        {
                            if ((i = stream.EndRead(ar)) > 0)
                            {
                                fs.Write(buffer, 0, i);
                                //继续异步读取
                                stream.Flush();
                                //下载时引发事件
                                DownLoadStatus[0] = "正在下载...";
                                int x = int.Parse(DownLoadStatus[1]);
                                DownLoadStatus[1] = (x + i).ToString();
                                if (FtpConnectStateEvent != null)
                                {
                                    FtpConnectStateEvent(DownLoadStatus, new EventArgs());
                                }
                                stream.BeginRead(buffer, 0, buffer.Length, StreamAsyncCallback, stream);
                                Thread.Sleep(10);
                            }
                            else
                            {
                                stream.Close();
                                fs.Close();
                                DownLoadStatus[0] = "下载完成...";
                                DownLoadStatus[1] = DownLoadStatus[2];
                                if (FtpConnectStateEvent != null)
                                {
                                    FtpConnectStateEvent(DownLoadStatus, new EventArgs());
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (FtpErrorEvent != null)
                        {
                            FtpErrorEvent(ex.Message, new EventArgs());
                        }
                    }
                }
            }
            /// <summary>
            /// 该报头拿到的文件大小都是多3072B
            /// </summary>
            /// <param name="response"></param>
            /// <returns></returns>
            private long GetFileLength(WebResponse response)
            {
                long ContentLength =0;
                if (long.TryParse(response.Headers.Get("Content-Length"), out ContentLength))
                {
                    return ContentLength;
                }
                return 0;
            }        #endregion        #region 组件生成的代码        /// <summary>
            /// 必需的设计器变量。
            /// </summary>
            IContainer components = null;        /// <summary> 
            /// 清理所有正在使用的资源。
            /// </summary>
            /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                    IsHasExit = true;
                    if (fs != null)
                        fs.Dispose();
                    if (stream != null)
                        stream.Dispose();
                    Thread.Sleep(100);
                }
                base.Dispose(disposing);
            }        #region 组件设计器生成的代码        /// <summary>
            /// 设计器支持所需的方法 - 不要
            /// 使用代码编辑器修改此方法的内容。
            /// </summary>
            private void InitializeComponent()
            {
                components = new Container();
            }        #endregion        #endregion