我现在需要实现的一个功能是把远程IP :192.168.150.12下的F盘的DATA文件下的所有文件用列表显示出来,然后用户来选择文件,然后上传到本地,这个功能如何实现呢?求解。

解决方案 »

  1.   

    1.获取文件夹及文件夹下的文件
    2.获取选中的文件夹或文件夹下的文件(路径和文件名)
    3.通过路径创建文件夹或将文件下载到指定目录下。
    部分代码参考:
    /// <summary>
            /// 文件备份
            /// </summary>
            public void BackUpImages()
            {           string souce1 = "Resources\\Images";
                if (Directory.Exists(souce1))
                {
                    //filePath.Split(':')[0] + ":\\ImageBackUp\\"
                    string backPath = backupPicPath + DateTime.Now.ToString("yyyyMMddhh") + "images";
                    //获取该目录下的文件夹
                    string[] directoryPaths = Directory.GetDirectories(souce1);                //获取该目录下的文件
                    string[] filepaths = Directory.GetFiles(souce1);
                    CopyFile(filepaths, souce1, backPath);                for (int i = 0; i < directoryPaths.Length; i++)
                    {
                        souce1 = directoryPaths[i];
                        //获取该目录下的文件
                        string[] aFiles = Directory.GetFiles(souce1);
                        CopyFile(aFiles, souce1, backPath);                    //获取该目录下的文件夹
                        string[] directoryPathChild = Directory.GetDirectories(souce1);
                        int indexPath = souce1.LastIndexOf('\\');
                        string fileName = souce1.Remove(0, indexPath + 1);
                        string backPathChild = backPath + "\\" + fileName;
                        //获取该文件夹下是否存在文件夹
                        for (int j = 0; j < directoryPathChild.Length; j++)
                        {
                            souce1 = directoryPathChild[j];
                            string[] aFilesChild = Directory.GetFiles(souce1);
                            CopyFile(aFilesChild, souce1, backPathChild);
                        }
                    }
                }
            }        /// <summary>
            /// 
            /// </summary>
            /// <param name="filePath">图片路径</param>
            /// <param name="directoryPaths">文件夹源路径</param>
            /// <param name="backPath">备份路径</param>
            public void CopyFile(string[] filePath, string directoryPaths, string backPath)
            {
                if (filePath.Length>0)
                {
                    int indexPath = directoryPaths.LastIndexOf('\\');
                    string fileName = directoryPaths.Remove(0, indexPath + 1);
                    backPath += "\\" + fileName + "\\";
                    for (int i = 0; i < filePath.Length; i++)
                    {
                        FileInfo fi = new FileInfo(filePath[i]);                    if (!Directory.Exists(backPath))
                        {
                            Directory.CreateDirectory(backPath);
                        }
                        if (!File.Exists(backPath + fi.Name))
                        {
                            File.Copy(filePath[i], backPath + fi.Name);
                        }
                    }
                }
            }
      

  2.   

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;using System.Net;
    using System.IO;
    namespace FtpTree
    {
        public partial class GetFtpTree : Form
        {
            public GetFtpTree()
            {
                InitializeComponent();
                tbFtp.Text = "ftp://192.168.150.63";
            }
            FtpWeb ftpWeb = null;
            
            public class FtpWeb
            {
               // public string ftpServerIP;
                public string ftpRemotePath;
                public string ftpUserID;
                public string ftpPassword;
                public string ftpURI;
                public string ftpPath;
                /// <summary>  
                /// 连接FTP  
                /// </summary>  
                /// <param name="FtpServerIP">FTP连接地址</param>  
                /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>  
                /// <param name="FtpUserID">用户名</param>  
                /// <param name="FtpPassword">密码</param>  
                public FtpWeb(string FtpURI, string FtpRemotePath, string FtpUserID, string FtpPassword)
                {
                //    ftpServerIP = FtpServerIP;
                    ftpRemotePath = FtpRemotePath;
                    ftpUserID = FtpUserID;
                    ftpPassword = FtpPassword;
                   // ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
                  //  ftpURI = "ftp://" + ftpServerIP + "/" ;
                    ftpURI = FtpURI;
                    ftpPath = ftpURI + ftpRemotePath+"/";
                }
                public FtpWeb()
                {
                }
                /// <summary>  
                /// 获取FTP文件列表包括文件夹  
                /// </summary>  
                /// <returns></returns>  
                public string[] GetAllList(string url, string userid, string password)
                {
                    List<string> list = new List<string>();
                    FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(url));
                    req.Credentials = new NetworkCredential(userid, password);
                    req.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                    req.UseBinary = true;
                    req.UsePassive = true;
                    try
                    {
                        using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
                        {
                            using (StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default))//这里encoding.Default防止中文乱码
                            {
                                string s;
                                while ((s = sr.ReadLine()) != null)
                                {
                                    list.Add(s);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                    return list.ToArray();
                }
            }        private void btn_connect_Click(object sender, EventArgs e)
            {
                
                TreeNode preNode = tv.Nodes["Node0"];
                preNode.Nodes.Clear();
                ftpWeb = new FtpWeb(tbFtp.Text, null,"anonymous", "");//实际应用
                tv.TopNode.Text = tbFtp.Text;
                GetDir(ftpWeb.ftpPath, ftpWeb.ftpUserID, ftpWeb.ftpPassword, preNode);
               
            }        private void GetDir(string ftpPath, string ftpUserID, string ftpPassword,TreeNode preNode)
            {
                //"ftp://192.168.150.63/2013_5_29/4472B/"
                string[] listArray = ftpWeb.GetAllList(ftpPath, ftpUserID, ftpPassword);
                TreeNode TempNode = preNode;
                List<string> dirList = new List<string>();
                if (listArray.Length != 0)
                {
                    for (int i = 0; i < listArray.Length; i++)//去除文件
                    {
                        if ((listArray[i].Remove(29)).Contains("<DIR>"))//判断是否是文件夹,截取前29位信息,如果包含<DIR>则是文件夹
                        {
                            dirList.Add(listArray[i].Remove(0, 39));
                        }
                    }
                    if (dirList.Count != 0)
                    {
                        foreach (string dir in dirList)
                        {
                            TempNode.Nodes.Add(dir, dir);
                            preNode = TempNode.Nodes[dir];
                            GetDir( ftpPath + dir + "/", ftpUserID, ftpPassword, preNode);
                        }
                    }
                }
            }        private void tv_AfterSelect(object sender, TreeViewEventArgs e)
            {
                //清空list集合
                checkedListBox1.Items.Clear();
                string path = tv.SelectedNode.FullPath.ToString();
                path = path.Replace("\\","/").ToString();
                string temp = string.Empty;
                if (path.Length > 20)
                {
                    temp = path.Remove(0, 20);//取消路径中的ftp://192.168.150.63
                    int count = ContainCount(temp, "/", true);            
                    //这是去掉FTP后的字符串/2013_5_30/5105
                    if (count >= 2)//判断/是否含有2个
                    {
                        string[] listArray = ftpWeb.GetAllList(path+"/", ftpWeb.ftpUserID, ftpWeb.ftpPassword);
                        
                        for (int i = 0; i < listArray.Length; i++)
                        {
                            //去掉无用的字符串,只留文件名
                            if (listArray[i].EndsWith(".tdms", StringComparison.CurrentCulture))
                            {
                                string filename = listArray[i].Remove(0, 39);
                                checkedListBox1.Items.Add(filename);
                            }                    }
                       
                    }            }
            }
            /// <summary>
            /// 文件上传
            /// </summary>
            /// <param name="filename"></param>
            /// <returns></returns>
            public bool Upload(string filename)
            {
                try
                {
                    FileInfo fileInf = new FileInfo(filename);
                    string uri = "ftp://" + "192.168.150.63" + "/" + fileInf.Name;
                    FtpWebRequest reqFTP;                
                    // 根据uri创建FtpWebRequest对象 
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));                // ftp用户名和密码
                    reqFTP.Credentials = new NetworkCredential("anonymous", "");                // 默认为true,连接不会被关闭
                    // 在一个命令之后被执行
                    reqFTP.KeepAlive = false;                // 指定执行什么命令
                    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;                // 指定数据传输类型
                    reqFTP.UseBinary = true;                // 上传文件时通知服务器文件的大小
                    reqFTP.ContentLength = fileInf.Length;                                // 缓冲大小设置为2kb
                    int buffLength = 2048;                byte[] buff = new byte[buffLength];
                    int contentLen;                // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
                    FileStream fs = fileInf.OpenRead();
                    try
                    {
                        // 把上传的文件写入流
                        Stream strm = reqFTP.GetRequestStream();                    // 每次读文件流的2kb
                        contentLen = fs.Read(buff, 0, buffLength);                    // 流内容没有结束
                        while (contentLen != 0)
                        {
                            // 把内容从file stream 写入 upload stream
                            strm.Write(buff, 0, contentLen);                        contentLen = fs.Read(buff, 0, buffLength);
                        }                    // 关闭两个流
                        strm.Close();
                        fs.Close();
                        return true;
                    }
                    catch (Exception e)
                    {
                        //MessageBox.Show(e.Message, "上传文件失败");
                        return false;
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "失败");
                    return false;
                }        }
            public static int ContainCount(string input, string findstr, bool ignoreCase)
            {
                if (ignoreCase)
                {
                    input = input.ToLower();                findstr = findstr.ToLower();
                }            int count = 0;            for (int i = 0; (i = input.IndexOf(findstr, i)) >= 0; i = i + findstr.Length)
                {
                    count++;
                }            return count;
            }        private void btn_upload_Click(object sender, EventArgs e)
            {
               bool bTest = Upload("1.txt");        }        private void btn_exit_Click(object sender, EventArgs e)
            {
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }        private void btn_AllSelect_Click(object sender, EventArgs e)
            {
                for (int i = 0 ; i < checkedListBox1.Items.Count ; i++)
                {
                    checkedListBox1.SetItemChecked(i,true);
                }
               
            }        private void btn_AllNoSelect_Click(object sender, EventArgs e)
            {
                for (int i = 0; i < checkedListBox1.Items.Count; i++)
                {
                    checkedListBox1.SetItemChecked(i, false);
                }
            }
        }}
    这是我写的代码,目前怎么在上传的时候老报错。
      

  3.   


    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;using System.Net;
    using System.IO;
    namespace FtpTree
    {
        public partial class GetFtpTree : Form
        {
            public GetFtpTree()
            {
                InitializeComponent();
                tbFtp.Text = "ftp://192.168.150.63";
            }
            FtpWeb ftpWeb = null;
            
            public class FtpWeb
            {
               // public string ftpServerIP;
                public string ftpRemotePath;
                public string ftpUserID;
                public string ftpPassword;
                public string ftpURI;
                public string ftpPath;
                /// <summary>  
                /// 连接FTP  
                /// </summary>  
                /// <param name="FtpServerIP">FTP连接地址</param>  
                /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>  
                /// <param name="FtpUserID">用户名</param>  
                /// <param name="FtpPassword">密码</param>  
                public FtpWeb(string FtpURI, string FtpRemotePath, string FtpUserID, string FtpPassword)
                {
                //    ftpServerIP = FtpServerIP;
                    ftpRemotePath = FtpRemotePath;
                    ftpUserID = FtpUserID;
                    ftpPassword = FtpPassword;
                   // ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
                  //  ftpURI = "ftp://" + ftpServerIP + "/" ;
                    ftpURI = FtpURI;
                    ftpPath = ftpURI + ftpRemotePath+"/";
                }
                public FtpWeb()
                {
                }
                /// <summary>  
                /// 获取FTP文件列表包括文件夹  
                /// </summary>  
                /// <returns></returns>  
                public string[] GetAllList(string url, string userid, string password)
                {
                    List<string> list = new List<string>();
                    FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(url));
                    req.Credentials = new NetworkCredential(userid, password);
                    req.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                    req.UseBinary = true;
                    req.UsePassive = true;
                    try
                    {
                        using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
                        {
                            using (StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default))//这里encoding.Default防止中文乱码
                            {
                                string s;
                                while ((s = sr.ReadLine()) != null)
                                {
                                    list.Add(s);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                    return list.ToArray();
                }
            }        private void btn_connect_Click(object sender, EventArgs e)
            {
                
                TreeNode preNode = tv.Nodes["Node0"];
                preNode.Nodes.Clear();
                ftpWeb = new FtpWeb(tbFtp.Text, null,"anonymous", "");//实际应用
                tv.TopNode.Text = tbFtp.Text;
                GetDir(ftpWeb.ftpPath, ftpWeb.ftpUserID, ftpWeb.ftpPassword, preNode);
               
            }        private void GetDir(string ftpPath, string ftpUserID, string ftpPassword,TreeNode preNode)
            {
                //"ftp://192.168.150.63/2013_5_29/4472B/"
                string[] listArray = ftpWeb.GetAllList(ftpPath, ftpUserID, ftpPassword);
                TreeNode TempNode = preNode;
                List<string> dirList = new List<string>();
                if (listArray.Length != 0)
                {
                    for (int i = 0; i < listArray.Length; i++)//去除文件
                    {
                        if ((listArray[i].Remove(29)).Contains("<DIR>"))//判断是否是文件夹,截取前29位信息,如果包含<DIR>则是文件夹
                        {
                            dirList.Add(listArray[i].Remove(0, 39));
                        }
                    }
                    if (dirList.Count != 0)
                    {
                        foreach (string dir in dirList)
                        {
                            TempNode.Nodes.Add(dir, dir);
                            preNode = TempNode.Nodes[dir];
                            GetDir( ftpPath + dir + "/", ftpUserID, ftpPassword, preNode);
                        }
                    }
                }
            }        private void tv_AfterSelect(object sender, TreeViewEventArgs e)
            {
                //清空list集合
                checkedListBox1.Items.Clear();
                string path = tv.SelectedNode.FullPath.ToString();
                path = path.Replace("\\","/").ToString();
                string temp = string.Empty;
                if (path.Length > 20)
                {
                    temp = path.Remove(0, 20);//取消路径中的ftp://192.168.150.63
                    int count = ContainCount(temp, "/", true);            
                    //这是去掉FTP后的字符串/2013_5_30/5105
                    if (count >= 2)//判断/是否含有2个
                    {
                        string[] listArray = ftpWeb.GetAllList(path+"/", ftpWeb.ftpUserID, ftpWeb.ftpPassword);
                        
                        for (int i = 0; i < listArray.Length; i++)
                        {
                            //去掉无用的字符串,只留文件名
                            if (listArray[i].EndsWith(".tdms", StringComparison.CurrentCulture))
                            {
                                string filename = listArray[i].Remove(0, 39);
                                checkedListBox1.Items.Add(filename);
                            }                    }
                       
                    }            }
            }
            /// <summary>
            /// 文件上传
            /// </summary>
            /// <param name="filename"></param>
            /// <returns></returns>
            public bool Upload(string filename)
            {
                try
                {
                    FileInfo fileInf = new FileInfo(filename);
                    string uri = "ftp://" + "192.168.150.63" + "/" + fileInf.Name;
                    FtpWebRequest reqFTP;                
                    // 根据uri创建FtpWebRequest对象 
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));                // ftp用户名和密码
                    reqFTP.Credentials = new NetworkCredential("anonymous", "");                // 默认为true,连接不会被关闭
                    // 在一个命令之后被执行
                    reqFTP.KeepAlive = false;                // 指定执行什么命令
                    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;                // 指定数据传输类型
                    reqFTP.UseBinary = true;                // 上传文件时通知服务器文件的大小
                    reqFTP.ContentLength = fileInf.Length;                                // 缓冲大小设置为2kb
                    int buffLength = 2048;                byte[] buff = new byte[buffLength];
                    int contentLen;                // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
                    FileStream fs = fileInf.OpenRead();
                    try
                    {
                        // 把上传的文件写入流
                        Stream strm = reqFTP.GetRequestStream();                    // 每次读文件流的2kb
                        contentLen = fs.Read(buff, 0, buffLength);                    // 流内容没有结束
                        while (contentLen != 0)
                        {
                            // 把内容从file stream 写入 upload stream
                            strm.Write(buff, 0, contentLen);                        contentLen = fs.Read(buff, 0, buffLength);
                        }                    // 关闭两个流
                        strm.Close();
                        fs.Close();
                        return true;
                    }
                    catch (Exception e)
                    {
                        //MessageBox.Show(e.Message, "上传文件失败");
                        return false;
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "失败");
                    return false;
                }        }
            public static int ContainCount(string input, string findstr, bool ignoreCase)
            {
                if (ignoreCase)
                {
                    input = input.ToLower();                findstr = findstr.ToLower();
                }            int count = 0;            for (int i = 0; (i = input.IndexOf(findstr, i)) >= 0; i = i + findstr.Length)
                {
                    count++;
                }            return count;
            }        private void btn_upload_Click(object sender, EventArgs e)
            {
               bool bTest = Upload("1.txt");        }        private void btn_exit_Click(object sender, EventArgs e)
            {
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }        private void btn_AllSelect_Click(object sender, EventArgs e)
            {
                for (int i = 0 ; i < checkedListBox1.Items.Count ; i++)
                {
                    checkedListBox1.SetItemChecked(i,true);
                }
               
            }        private void btn_AllNoSelect_Click(object sender, EventArgs e)
            {
                for (int i = 0; i < checkedListBox1.Items.Count; i++)
                {
                    checkedListBox1.SetItemChecked(i, false);
                }
            }
        }}