ftp客户端程序

    最近做一个ftp客户端程序,有用到这些代码。与现在ftp客户端最大不同是,可以根据更新时间以及文件后缀名来过滤文件这对一个项目经理来说无疑可以节省很多时间、精力。

    public partial class mainForm : Form
    {
        string path;    //目录名 也可以用相当路径
        string filter = "*.*";        //文件类型
        int m_numFiles = 0;        //文件总数
        ArrayList m_pathList = new ArrayList();//包含所有文件路径的数组
        string[] files;            //所有文件名
        DateTime time;

        string m_strWinSCPPath;

        public mainForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            m_strWinSCPPath = System.IO.Path.Combine(RunPath, "WinSCP");
            SetDateTime.Value =DateTime.Parse( DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
             
        }

        private void initDate()
        {
            this.lvList.Visible = true;
            ParseDirectory(path, "*.*");
            files = CreatePathList();        //生成文件名数组

            if (files == null)
            {
                throw new Exception(String.Concat("No file found in ", path));
            }
        }

        private string[] CreatePathList()
        {
            if (m_numFiles <= 0)
            {
                return null;
            }

            string[] str = new string[m_numFiles];
            int index = 0;

            try
            {
                IEnumerator pathIter = m_pathList.GetEnumerator();
                while (pathIter.MoveNext())
                {
                    string[] ar = (string[])(pathIter.Current);
                    IEnumerator fileIter = ar.GetEnumerator();
                    while (fileIter.MoveNext())
                    {
                        str[index] = (string)(fileIter.Current);
                        ++index;
                    }
                }
            }
            catch (Exception e)
            {
                Console.Write(e.ToString());
                return null;
            }

            return str;

        }

        private void ParseDirectory(string path, string p)
        {
            try
            {

            string[] dirs = Directory.GetDirectories(path);//得到子目录
            IEnumerator iter = dirs.GetEnumerator();
            while (iter.MoveNext())
            {
                string str = (string)(iter.Current);
                ParseDirectory(str, filter);
            }
            time = this.SetDateTime.Value;
            string filters = this.TxtStyle.Text.Trim();
            string[] filte = filters.Split(';');
            int j = filte.Length;
            while (j > 0)
            {
                txtMessage.Text = path;
                Application.DoEvents();
                string[] files = Directory.GetFiles(path,"*"+ filte[j-1]);


                if (files.Length > 0)
                {
                    foreach (string filename in files)
                    {

                        FileInfo inf = new FileInfo(filename);


                        float value = inf.Length / 1024 / 1024;
                        m_numFiles += files.Length;
                        m_pathList.Add(files);

                        if (inf.LastWriteTime > time)
                        {
                            //foreach (string str in filte)
                           // {
                               // if (inf.Extension == str)
                                //{
                                    ListViewItem lvItem = new ListViewItem();
                                    lvItem.Text = inf.Name;
                                    lvItem.Checked = true;
                                    lvItem.Tag = inf.DirectoryName.ToString() + """" + inf.Name.ToString();
                                    lvItem.SubItems.Add(inf.DirectoryName.ToString() + """" + inf.Name.ToString());
                                    lvItem.SubItems.Add(inf.LastWriteTime.ToString());
                                    lvList.Items.Add(lvItem);
                                   
                               // }
                           // }
                        }
                    }
                   
                }
              j--;
            }

            }
            catch (Exception e)
            {

                //throw;
            }
        }

        
        private void btnUpload_Click(object sender, EventArgs e)   //上传开始
        {
            string strWinSCP = System.IO.Path.Combine(m_strWinSCPPath, "WinSCP.com");
            if (!System.IO.File.Exists(strWinSCP))
            {
                MessageBox.Show("找不到" + strWinSCP);
                return;
            }

            string strScriptFile = CreateScriptFile();
            //return;

            ProcessStartInfo start = new ProcessStartInfo(strWinSCP);
            start.Arguments = "/script=" + System.IO.Path.Combine(m_strWinSCPPath, strScriptFile);  //设置命令参数
            start.CreateNoWindow = true;//不显示dos命令行窗口
            start.RedirectStandardOutput = true;//
            start.RedirectStandardInput = true;//
            start.UseShellExecute = false;//是否指定操作系统外壳进程启动程序
            Process p = Process.Start(start);
            StreamReader reader = p.StandardOutput;//截取输出流
            string line = reader.ReadLine();//每次读取一行
            txtMessage.Text = "开始上传...";
            while (!reader.EndOfStream)
            {
                txtMessage.Text = line + ""r"n" + txtMessage.Text;
                Application.DoEvents();
                System.Threading.Thread.Sleep(100);
                line = reader.ReadLine();
            }
            p.WaitForExit();//等待程序执行完退出进程
            p.Close();//关闭进程
            reader.Close();//关闭流
            System.IO.File.Delete(strScriptFile);
            txtMessage.Text ="上传完成."r"n" + txtMessage.Text;
        }

        private string CreateScriptFile()
        {
            string strFileName =System.IO.Path.Combine(m_strWinSCPPath, DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt");
            const string SCRIPT_HEARD = "option batch on "r"noption confirm off "r"nopen {0}"r"n{1}"r"nclose"r"nexit";
            string strFilelist="";
            foreach (ListViewItem item in lvList.Items)
            {
                if (item.Checked)
                {
                    string strLocalPath = item.SubItems[1].Text;
                    string strRemotePath = strLocalPath.Replace(lab.Text, "");
                    strRemotePath = strRemotePath.Replace("""", "/");
                    strFilelist += "put """ + strLocalPath + """ """ + strRemotePath + """"r"n" ;
                }
            }

            string strScript = "";
            if (!string.IsNullOrEmpty(strFilelist))
            {
                strScript = string.Format(SCRIPT_HEARD, txtSession.Text, strFilelist);
            }
            System.IO.File.WriteAllText(strFileName, strScript);
            return strFileName;
        }

        private void btnSelectDirectory_Click(object sender, EventArgs e)
        {
            if ( fbdSelect.ShowDialog()==DialogResult.OK)
            {
                if (!string.IsNullOrEmpty( fbdSelect.SelectedPath))
                {
                    path = fbdSelect.SelectedPath.ToString();
                    lab.Text = path;
                    btnShowList.PerformClick();
                }
            }
        }

       

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(lab.Text))
            {
                btnSelectDirectory.PerformClick();
                return;
            }
            btnUpload.Enabled = false;
            this.lvList.Items.Clear();

            initDate();
            //lvList.CheckBoxes = true;
            //lvList.Items[0].Selected = true;
            //this.btnUpload.Visible = true;
            txtMessage.Text = "列表完成.";
            btnUpload.Enabled = true;
        }


        string m_strRunPath = "";
        private string RunPath
        {
            get
            {
                if (string.IsNullOrEmpty(m_strRunPath))
                {
                    m_strRunPath = Application.StartupPath;
                }
                return m_strRunPath;
            }

        }

        private void TxtStyle_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar==13)
            {
                btnShowList.PerformClick();
            }
        }

        private void btnCreateSession_Click(object sender, EventArgs e)
        {
            string strFile = System.IO.Path.Combine(m_strWinSCPPath, "WinSCP.exe");
            if (System.IO.File.Exists(strFile))
            {
                System.Diagnostics.Process.Start(strFile );
            }
            else
            {
                MessageBox.Show("找不到" + strFile);
            }
            
        }

    }
}

    

 

posted on 2008-11-28 11:32  prayforsmile  阅读(321)  评论(0编辑  收藏  举报