您好,欢迎访问三七文档
当前位置:首页 > IT计算机/网络 > 数据库 > 使用C#实现FTP的文件上传和下载
实现FTP的文件上传和下载搭建好FTP服务器后,借助.NETFramework提供的类,实现文件的上传和下载是比较简单的事情,下面我们用C#来实现这一过程。程序主界面下图便是样例程序的界面,输入登录FTP的“用户名”和“密码”,点击“上传”按钮,弹出“打开文件”对话框,选择要上传的文件,“确定”后开开始将文件上传到指定的FTP服务器的文件夹中。下载文件时,点击“刷新文件列表”,获得FTP服务器上指定文件夹的文件列表,选中要下载的文件,点击下载,将文件下载到本地。文件上传因为“上传”要使用到流、多线程、网络等技术,故需要导入.NETFramework相关的名称空间:System.IO、System.Threading、System.Net。实现Ftp的文件上传的核心类便是FtpWebRequest类。下面是“上传”按钮的Click事件代码:1://上传按钮代码2:privatevoidbtnUpload_Click(objectsender,EventArgse)3:{4:OpenFileDialogopenDlg=newOpenFileDialog();5:if(openDlg.ShowDialog()!=DialogResult.OK)return;6:7:stringfileName=openDlg.FileName;8:this.lblFileName.Text=fileName;9:Threadthread=newThread(newThreadStart(delegate()10:{11:this.UploadFileByFtpWebRequest(fileName,);12:}));13:thread.Start();14:}下面是UploadFileByFtpWebRequest方法的代码:1:privateboolUploadFileByFtpWebRequest(stringfileName,stringftpServerIP,stringpath,stringuserName,stringpassword)2:{3:boolresult=true;4:stringurl=string.Format(ftp://{0}/{1}/{2},ftpServerIP,path,fileName.Substring(fileName.LastIndexOf(@\)+1));5:6:FtpWebRequestrequest=(FtpWebRequest)WebRequest.Create(url);7:request.Credentials=newNetworkCredential(userName,password);8:request.Method=WebRequestMethods.Ftp.UploadFile;9:10:Streamstream=request.GetRequestStream();11:FileStreamfileStream=newFileStream(fileName,FileMode.Open);12:13:intpackageSize=1024*1024;14:intpackageCount=(int)(fileStream.Length/packageSize);15:intrest=(int)(fileStream.Length%packageSize);16:this.BeginInvoke(newDoSomething(delegate()17:{18:this.pbarProcessUpload.Maximum=packageCount;19:if(rest!=0)this.pbarProcessUpload.Maximum+=1;20:}));21:22:for(intindex=0;indexpackageCount;index++)23:{24:byte[]buffer=newbyte[packageSize];25:fileStream.Read(buffer,0,buffer.Length);26:27:stream.Write(buffer,0,buffer.Length);28:29:this.BeginInvoke(newDoSomething(delegate()30:{31:this.pbarProcessUpload.Value=index;32:}));}34:35:if(rest!=0)36:{37:byte[]buffer=newbyte[rest];38:fileStream.Read(buffer,0,buffer.Length);39:40:stream.Write(buffer,0,buffer.Length);41:42:this.BeginInvoke(newDoSomething(delegate()43:{44:this.pbarProcessUpload.Value+=1;45:}));46:}47:48:stream.Close();49:fileStream.Close();50:51:this.BeginInvoke(newDoSomething(delegate()52:{53:this.pbarProcessUpload.Value=0;54:}));55:56:returnresult;57:}58:privatedelegatevoidDoSomething();
本文标题:使用C#实现FTP的文件上传和下载
链接地址:https://www.777doc.com/doc-6464714 .html