欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# winfrom 模拟ftp文件管理实现代码

程序员文章站 2024-02-15 23:28:22
复制代码 代码如下:using system; using system.collections.generic; using system.text; using sys...

复制代码 代码如下:

using system;
using system.collections.generic;
using system.text;
using system.net;
using system.io;
using system.windows.forms;

 
namespace convertdata
{
    class ftpupdown
    {

        string ftpserverip;
        string ftpuserid;
        string ftppassword;
        ftpwebrequest reqftp;

        private void connect(string path)//连接ftp
        {
            // 根据uri创建ftpwebrequest对象
            reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(path));
            // 指定数据传输类型
            reqftp.usebinary = true;
            // ftp用户名和密码
            reqftp.credentials = new networkcredential(ftpuserid, ftppassword);
        }

        public ftpupdown(string ftpserverip, string ftpuserid, string ftppassword)
        {
            this.ftpserverip = ftpserverip;
            this.ftpuserid = ftpuserid;
            this.ftppassword = ftppassword;
        }

        //都调用这个
        private string[] getfilelist(string path, string wrmethods)//上面的代码示例了如何从ftp服务器上获得文件列表
        {
            string[] downloadfiles;
            stringbuilder result = new stringbuilder();
            try
            {
                connect(path);
                reqftp.method = wrmethods;
                webresponse response = reqftp.getresponse();
                streamreader reader = new streamreader(response.getresponsestream(), system.text.encoding.default);//中文文件名
                string line = reader.readline();
                while (line != null)
                {
                    result.append(line);
                    result.append("\n");
                    line = reader.readline();
                }
                // to remove the trailing '\n'
                result.remove(result.tostring().lastindexof('\n'), 1);
                reader.close();
                response.close();
                return result.tostring().split('\n');
            }
            catch (exception ex)
            {
                system.windows.forms.messagebox.show(ex.message);
                downloadfiles = null;
                return downloadfiles;
            }
        }

        public string[] getfilelist(string path)//上面的代码示例了如何从ftp服务器上获得文件列表
        {
            return getfilelist("ftp://" + ftpserverip + "/" + path, webrequestmethods.ftp.listdirectory);

        }

 

        public string[] getfilelist()//上面的代码示例了如何从ftp服务器上获得文件列表
        {
            return getfilelist("ftp://" + ftpserverip + "/", webrequestmethods.ftp.listdirectory);
        }

        public void upload(string filename) //上面的代码实现了从ftp服务器上载文件的功能
        {
            fileinfo fileinf = new fileinfo(filename);
            string uri = "ftp://" + ftpserverip + "/" + fileinf.name;
            connect(uri);//连接      
            // 默认为true,连接不会被关闭
            // 在一个命令之后被执行
            reqftp.keepalive = false;
            // 指定执行什么命令
            reqftp.method = webrequestmethods.ftp.uploadfile;
            // 上传文件时通知服务器文件的大小
            reqftp.contentlength = fileinf.length;
            // 缓冲大小设置为kb 
            int bufflength = 2048;

            byte[] buff = new byte[bufflength];
            int contentlen;
            // 打开一个文件流(system.io.filestream) 去读上传的文件
            filestream fs = fileinf.openread();
            try
            {
                // 把上传的文件写入流
                stream strm = reqftp.getrequeststream();
                // 每次读文件流的kb 
                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();
            }
            catch (exception ex)
            {
                messagebox.show(ex.message, "upload error");
            }
        }
        public bool download(string filepath, string filename, out string errorinfo)////上面的代码实现了从ftp服务器下载文件的功能
        {
            try
            {
                string onlyfilename = path.getfilename(filename);
                string newfilename = filepath + "\\" + onlyfilename;
                if (file.exists(newfilename))
                {
                    errorinfo = string.format("本地文件{0}已存在,无法下载", newfilename);
                    return false;
                }
                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;
            }
        }

        //删除文件

         public void deletefilename(string filename)
         {
             try
             {
                 fileinfo fileinf = new fileinfo(filename);
                 string uri = "ftp://" + ftpserverip + "/" + fileinf.name;
                 connect(uri);//连接        
                 // 默认为true,连接不会被关闭

                 // 在一个命令之后被执行

                 reqftp.keepalive = false;

                 // 指定执行什么命令

                 reqftp.method = webrequestmethods.ftp.deletefile;
                 ftpwebresponse response = (ftpwebresponse)reqftp.getresponse();
                 response.close();
             }
             catch (exception ex)
             {
                 messagebox.show(ex.message, "删除错误");
             }
         }

        //创建目录

        public void makedir(string dirname)
        {
            try
            {
                string uri = "ftp://" + ftpserverip + "/" + dirname;
                connect(uri);//连接       
                reqftp.method = webrequestmethods.ftp.makedirectory;
                ftpwebresponse response = (ftpwebresponse)reqftp.getresponse();
                response.close();
            }
            catch (exception ex)
            {
                messagebox.show(ex.message);
            }
        }
        //删除目录
        public void deldir(string dirname)
        {
            try
            {

                string uri = "ftp://" + ftpserverip + "/" + dirname;
                connect(uri);//连接       
                reqftp.method = webrequestmethods.ftp.removedirectory;
                ftpwebresponse response = (ftpwebresponse)reqftp.getresponse();
                response.close();
            }
            catch (exception ex)
            {
                messagebox.show(ex.message);
            }
        }

        //获得文件大小

        public long getfilesize(string filename)
        {
            long filesize = 0;
            try
            {
                fileinfo fileinf = new fileinfo(filename);
                string uri = "ftp://" + ftpserverip + "/" + fileinf.name;
                connect(uri);//连接       
                reqftp.method = webrequestmethods.ftp.getfilesize;
                ftpwebresponse response = (ftpwebresponse)reqftp.getresponse();
                filesize = response.contentlength;
                response.close();
            }
            catch (exception ex)
            {
                messagebox.show(ex.message);
            }
            return filesize;
        }

        //文件改名
        public void rename(string currentfilename, string newfilename)
        {
            try
            {
                fileinfo fileinf = new fileinfo(currentfilename);
                string uri = "ftp://" + ftpserverip + "/" + fileinf.name;
                connect(uri);//连接
                reqftp.method = webrequestmethods.ftp.rename;
                reqftp.renameto = newfilename;
                ftpwebresponse response = (ftpwebresponse)reqftp.getresponse();
                //stream ftpstream = response.getresponsestream();

                //ftpstream.close();
                response.close();
            }
            catch (exception ex)
            {
                messagebox.show(ex.message);
            }
        }

        //获得文件明晰
        public string[] getfilesdetaillist()
        {
            return getfilelist("ftp://" + ftpserverip + "/", webrequestmethods.ftp.listdirectorydetails);
        }
        //获得文件明晰
        public string[] getfilesdetaillist(string path)
        {
            return getfilelist("ftp://" + ftpserverip + "/" + path, webrequestmethods.ftp.listdirectorydetails);
        }

    }
}

上面为类,举例证明如何代用

复制代码 代码如下:

private void button1_click(object sender, eventargs e)//文件上传
        {
            ftpupdown ftpupdown = new ftpupdown("192.168.2.130:21", "wl","123456");
            ftpupdown.upload("e:\\other.rar");  
        }
 private void button3_click(object sender, eventargs e)//修改
        {
            ftpupdown ftpupdown = new ftpupdown("192.168.2.130:21", "wl", "123456");
            ftpupdown.rename("张三", "李四");
        }
 private void button4_click(object sender, eventargs e)//删除
        {
            ftpupdown ftpupdown = new ftpupdown("192.168.2.130:21", "wl", "123456");
            ftpupdown.deldir("张三");
        }
 private void button2_click(object sender, eventargs e)//添加
        {
            ftpupdown ftpupdown = new ftpupdown("192.168.2.130:21", "wl", "123456");
            ftpupdown.makedir(this.txt_name.text);
        }

 
//获得ftp文件的文件明晰,还为处理,能够获得所有的文件名称
 ftpupdown ftpupdown = new ftpupdown("192.168.2.130", "wl", "123456");
            string[] str = ftpupdown.getfilesdetaillist();
            int i = 1;
            foreach (string item in str)
            {
                string[] name = item.split(' ');
                txt_name.text += name[name.length - 1] + ";";
                i++;
            }
            label1.text = i.tostring();