发布日期:2023-03-31来源:武汉北大青鸟武汉校区作者:武汉宏鹏
使用C#实现FTP的文件上传和下载-武汉北大青鸟C#技术
搭建好FTP服务器后,借助.NET Framework提供的类,实现文件的上传和下载是比较简单的事情,下面我们用C#来实现这一过程。
程序主界面
下图便是样例程序的界面,输入登录FTP的“用户名”和“密码”,点击“上传”按钮,弹出“打开文件”对话框,选择要上传的文件,“确定”后开开始将文件上传到指定的FTP服务器的文件夹中。下载文件时,点击“刷新文件列表”,获得FTP服务器上指定文件夹的文件列表,选中要下载的文件,点击下载,将文件下载到本地。
文件上传
因为“上传”要使用到流、多线程、网络等技术,故需要导入.NET Framework相关的名称空间:System.IO、System.Threading、System.Net。
实现Ftp的文件上传的核心类便是FtpWebRequest类。下面是“上传”按钮的Click事件代码:
1: //上传按钮代码
2: private void btnUpload_Click(object sender, EventArgs e)
3: {
4: OpenFileDialog openDlg = new OpenFileDialog();
5: if (openDlg.ShowDialog() != DialogResult.OK) return;
6:
7: string fileName = openDlg.FileName;
8: this.lblFileName.Text = fileName;
9: Thread thread = new Thread(new ThreadStart(delegate()
10: {
11: this.UploadFileByFtpWebRequest(fileName, this.txtFTPServerIP.Text, this.txtPath.Text, this.txtUserName.Text, this.txtPassword.Text);
12: }));
13: thread.Start();
14: }
下面是UploadFileByFtpWebRequest方法的代码:
1: private bool UploadFileByFtpWebRequest(string fileName, string ftpServerIP, string path, string userName, string password)
2: {
3: bool result = true;
4: string url = string.Format("ftp://{0}/{1}/{2}", ftpServerIP, path, fileName.Substring(fileName.LastIndexOf(@"\") + 1));
5:
6: FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
7: request.Credentials = new NetworkCredential(userName, password);
8: request.Method = WebRequestMethods.Ftp.UploadFile;
9:
10: Stream stream = request.GetRequestStream();
11: FileStream fileStream = new FileStream(fileName, FileMode.Open);
12:
13: int packageSize = 1024 * 1024;
14: int packageCount = (int)(fileStream.Length / packageSize);
15: int rest = (int)(fileStream.Length % packageSize);
16: this.BeginInvoke(new DoSomething(delegate()
17: {
18: this.pbarProcessUpload.Maximum = packageCount;
19: if (rest != 0) this.pbarProcessUpload.Maximum += 1;
20: }));
21:
22: for (int index = 0; index < packageCount; index++)
23: {
24: byte[] buffer = new byte[packageSize];
25: fileStream.Read(buffer, 0, buffer.Length);
26:
27: stream.Write(buffer, 0, buffer.Length);
28:
29: this.BeginInvoke(new DoSomething(delegate()
30: {
31: this.pbarProcessUpload.Value = index;
32: }));
33: }
34:
35: if (rest != 0)
36: {
37: byte[] buffer = new byte[rest];
38: fileStream.Read(buffer, 0, buffer.Length);
39:
40: stream.Write(buffer, 0, buffer.Length);
41:
42: this.BeginInvoke(new DoSomething(delegate()
43: {
44: this.pbarProcessUpload.Value +=1;
45: }));
46: }
47:
48: stream.Close();
49: fileStream.Close();
50:
51: this.BeginInvoke(new DoSomething(delegate()
52: {
53: this.pbarProcessUpload.Value = 0;
54: }));
55:
56: return result;
57: }
58: private delegate void DoSomething();
想了解更多C#技术请继续关注武汉北大青鸟官网,或者咨询电话:17740513250,欢迎加入北大青鸟武汉宏鹏光谷校区IT学习营地。
Copyright (c) 2006-2023 武汉宏鹏教育咨询有限公司 版权所有 All Rights Reserved.