
1 Ftp 上传
2
3 //上传FTP
4 public static string UpFtpServer="192.168.100.111";
5 public static string UpUserID= "sa";
6 public static string UpPassWord = "123456";
7
8 private void btnUp_Click(object sender, EventArgs e)
9 {
10 try
11 {
12 upFile();
13 }
14 catch (Exception ex)
15 {
16 MessageBoxEx.Show("上传文件发生错误,错误信息:" + ex.Message, "注意", MessageBoxButtons.OK, MessageBoxIcon.Information);
17 }
18 }
19
20 //上传文件到ftp
21 private void upFile()
22 {
23
24 #region 上传的文件路径
25 string directoryPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
26 int nIndex = directoryPath.LastIndexOf("\\");
27 directoryPath = directoryPath.Substring(0, nIndex);
28 directoryPath += "\\InData\\";
29 #endregion
30 string[] fileName = Directory.GetFiles(directoryPath, "*.txt");
31
32 Array array = Array.CreateInstance(typeof(string), fileName.Length);
33
34 fileName.CopyTo(array, 0);
35 IList<string> successname = new List<string>();
36 IList<string> failname = new List<string>();
37
38 string address = "", userName = "", pass = "", Report = "";
39
40 for (int i = 0; i < array.Length; i++)
41 {
42 if (File.Exists(array.GetValue(i).ToString()))
43 {
44 FileInfo fi = new FileInfo(array.GetValue(i).ToString());
45 FileStream fs = fi.OpenRead(); //以只读的模式创建一个文件流
46 Stream s = null;
47 try
48 {
49 address = UpFtpServer.Trim();
50 address = address.ToUpper().IndexOf("FTP://") < 0 ? ("FTP://" + address) : address;
51 userName = UpUserID.Trim();
52 pass = UpPassWord.Trim();
53
54 FtpWebRequest fwr = (FtpWebRequest)FtpWebRequest.Create(address + "/InData/" + Path.GetFileName(array.GetValue(i).ToString()));//创建一个ftpwebrequest对象
55
56 fwr.Credentials = new NetworkCredential(userName, pass);
57
58 fwr.KeepAlive = true; //执行完一次命令后是否保持连接
59 fwr.Method = WebRequestMethods.Ftp.UploadFile; //指出要执行的命令方式
60 fwr.UseBinary = true; //指出文件的数据传输类型
61 fwr.UsePassive = true;
62
63 int length = unchecked(Convert.ToInt32(fi.Length));
64 fwr.ContentLength = length;
65 s = fwr.GetRequestStream();
66
67 if (length <= 1000 * 1024) //文件上传的大小不能大于1000KB足够啦
68 {
69 byte[] b = new byte[length];
70 //先利用一个fileinfo跟一个文本文件关联起来 然后利用fileinfo的openread以只读的方式打开文本文件
71 //并返回一个filestream文件流
72 fs.Read(b, 0, length);
73 s.Write(b, 0, length);
74
75 if (successname.IndexOf(array.GetValue(i).ToString()) < 0)
76 {
77 successname.Add(array.GetValue(i).ToString());
78 }
79
80 Report = Report + "," + Path.GetFileName(array.GetValue(i).ToString());
81 }
82
83 fs.Close();
84 s.Close();
85 }
86 catch (Exception)
87 {
88 if (failname.IndexOf(array.GetValue(i).ToString()) < 0)
89 {
90 failname.Add(array.GetValue(i).ToString());
91 }
92 }
93 finally
94 {
95 fs.Close();
96 }
97 }
98
99 }
100
101 foreach (string filename in successname)
102 {
103 if (failname.IndexOf(filename) < 0)
104 {
105 File.Delete(filename); //上传完毕后就删除
106 }
107 }
108 MessageBoxEx.Show("本次共成功上传了" + successname.Count.ToString() + "个文件,失败" + failname.Count.ToString() + "个!", "注意", MessageBoxButtons.OK, MessageBoxIcon.Information);
109 }

1
2 private void btnDownlod_Click(object sender, EventArgs e)
3 {
4 try
5 {
6 #region 下载
7 //获取下载文件的文件名
8 List<string> DirctoryFile = GetDirctory("//");
9 MessageBox.Show("读取文件成功,共读取文件" + DirctoryFile.Count() + "条数据");
10 for (int i = 0; i < DirctoryFile.Count; i++)
11 {
12
13 //下载
14 if (download(DirctoryFile[i]))
15 {
16
17 }
18
19 }
20
21 MessageBox.Show("下载成功,共下载" + DirctoryFile.Count() + "个文件");
22 #endregion
23 }
24 catch
25 { }
26
27 }
28
29
30 /// 从ftp服务器上获得文件列表
31 /// </summary>
32 /// <param name="RequedstPath">服务器下的相对路径</param>
33 /// <returns></returns>
34 public List<string> GetDirctory(string RequedstPath)
35 {
36 List<string> strs = new List<string>();
37 try
38 {
39 string uri = "FTP://" + UpFtpServer + "/Download" + RequedstPath; //目标路径 path为服务器地址
40 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
41 // ftp用户名和密码
42 reqFTP.Credentials = new NetworkCredential(UpUserID, UpPassWord);
43 reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
44 WebResponse response = reqFTP.GetResponse();
45 StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
46 string line = reader.ReadLine();
47 while (line != null)
48 {
49 if (!line.Contains("<DIR>")) //不是文件夹
50 {
51 //string msg = line.Substring(39).ToUpper().Trim();
52 string[] msgArray = line.Split(' ');
53 string msg = msgArray[msgArray.Count() - 1].ToString();
54 if (msg.LastIndexOf("TXT") > 0)
55 {
56 strs.Add(msg);
57 }
58
59 }
60 line = reader.ReadLine();
61 }
62 reader.Close();
63 response.Close();
64 return strs;
65 }
66 catch (Exception ex)
67 {
68 ex.ToString();
69 }
70 return strs;
71 }
72 /// <summary>
73 /// 单个文件下载方法
74 /// </summary>
75 /// <param name="adss">保存文件的本地路径</param>
76 /// <param name="ftpadss">下载文件的FTP路径</param>
77 public bool download(string adss)
78 {
79 bool IsOk = false;
80
81 try
82 {
83 string directoryPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
84 int nIndex = directoryPath.LastIndexOf("\\");
85 directoryPath = directoryPath.Substring(0, nIndex);
86 directoryPath += "/Download/";
87 //FileMode常数确定如何打开或创建文件,指定操作系统应创建新文件。
88 //FileMode.Create如果文件已存在,它将被改写
89 FileStream outputStream = new FileStream(directoryPath + adss, FileMode.Create);
90 FtpWebRequest downRequest = (FtpWebRequest)WebRequest.Create(new Uri("FTP://" + UpFtpServer + "/Download/" + adss.ToString()));
91 downRequest.Credentials = new NetworkCredential(UpUserID, UpPassWord);
92 //设置要发送到 FTP 服务器的命令
93 downRequest.Method = WebRequestMethods.Ftp.DownloadFile;
94 downRequest.KeepAlive = true; //执行完一次命令后是否保持连接
95 downRequest.UseBinary = true; //指出文件的数据传输类型
96 downRequest.UsePassive = true;
97 FtpWebResponse response = (FtpWebResponse)downRequest.GetResponse();
98
99 Stream ftpStream = response.GetResponseStream();
100 long cl = response.ContentLength;
101 int bufferSize = 2048;
102 int readCount;
103 byte[] buffer = new byte[bufferSize];
104 readCount = ftpStream.Read(buffer, 0, bufferSize);
105
106 while (readCount > 0)
107 {
108 outputStream.Write(buffer, 0, readCount);
109 readCount = ftpStream.Read(buffer, 0, bufferSize);
110 }
111
112 ftpStream.Close();
113 outputStream.Close();
114 response.Close();
115
116
117 IsOk = true;
118
119 }
120 catch (Exception ex)
121 {
122 MessageBox.Show(ex.ToString());
123
124 IsOk = false;
125 }
126
127
128 return IsOk;
129
130 }
来源:https://www.cnblogs.com/haibing0107/p/5959216.html
