FTP的上传和下载

FTP的上传下载

  FTP的上传和下载,在工作中用到了,就记录下载,应该也是往年哪位大神写的吧,自己在记录一下。

定义属性Properties

  自己言语比较笨拙,注释上写的比较清楚,可以在代码中查看具体意思。

  1         #region Properties
  2 
  3         //FTP请求对象
  4         private FtpWebRequest Request = null;
  5 
  6         //FTP相应对象
  7         private FtpWebResponse Response = null;
  8 
  9         //FTP服务器地址
 10         private Uri _Uri;
 11         /// <summary>
 12         /// FTP服务器地址
 13         /// </summary>
 14         public Uri Uri
 15         {
 16             get
 17             {
 18                 if (_DirectoryPath == "/")
 19                 {
 20                     return _Uri;
 21                 }
 22                 else
 23                 {
 24                     string strUri = _Uri.ToString();
 25                     if (strUri.EndsWith("/"))
 26                     {
 27                         strUri = strUri.Substring(0, strUri.Length - 1);
 28                     }
 29                     return new Uri(strUri + this.DirectoryPath);
 30                 }
 31             }
 32             set
 33             {
 34                 if (value.Scheme != Uri.UriSchemeFtp)
 35                 {
 36                     throw new Exception("FTP地址错误");
 37                 }
 38                 _Uri = new Uri(value.GetLeftPart(UriPartial.Authority));
 39                 _DirectoryPath = value.AbsolutePath;
 40                 if (!_DirectoryPath.EndsWith("/"))
 41                 {
 42                     _DirectoryPath += "/";
 43                 }
 44             }
 45         }
 46 
 47         //当前目录
 48         private string _DirectoryPath;
 49         /// <summary>
 50         /// 当前目录
 51         /// </summary>
 52         public string DirectoryPath
 53         {
 54             get
 55             {
 56                 return _DirectoryPath;
 57             }
 58             set
 59             {
 60                 _DirectoryPath = value;
 61             }
 62         }
 63 
 64         // FTP登录用户
 65         private string _UserName;
 66         /// <summary>
 67         /// FTP登录用户
 68         /// </summary>
 69         public string UserName
 70         {
 71             get
 72             {
 73                 return _UserName;
 74             }
 75             set
 76             {
 77                 _UserName = value;
 78             }
 79         }
 80 
 81         // 错误信息
 82         private string _ErrorMsg;
 83         /// <summary>
 84         /// 错误信息
 85         /// </summary>
 86         public string ErrorMsg
 87         {
 88             get
 89             {
 90                 return _ErrorMsg;
 91             }
 92             set
 93             {
 94                 _ErrorMsg = value;
 95             }
 96         }
 97 
 98         // FTP登录密码
 99         private string _Password;
100         /// <summary>
101         ///  FTP登录密码
102         /// </summary>
103         public string Password
104         {
105             get
106             {
107                 return _Password;
108             }
109             set
110             {
111                 _Password = value;
112             }
113         }
114 
115         // 连接FTP服务器的代理服务
116         private WebProxy _Proxy = null;
117         /// <summary>
118         /// 连接FTP服务器的代理服务
119         /// </summary>
120         public WebProxy Proxy
121         {
122             get
123             {
124                 return _Proxy;
125             }
126             set
127             {
128                 _Proxy = value;
129             }
130         }
131 
132         #endregion
View Code

 方法Methods

定义打开FTP的方法

 1         /// <summary>
 2         /// 建立FTP连接,返回响应对象
 3         /// </summary>
 4         /// <param name="uri">FTP地址</param>
 5         /// <param name="FtpMethod">操作命令</param>
 6         /// <returns>响应对象</returns>
 7         private FtpWebResponse OpenFTP(Uri uri, string FtpMethod)
 8         {
 9             try
10             {
11                 Request = (FtpWebRequest)WebRequest.Create(uri);
12                 Request.Method = FtpMethod;
13                 //文件传输的类型是否是b
14                 Request.UseBinary = true;
15                 //连接FTP的凭证
16                 Request.Credentials = new NetworkCredential(this.UserName, this.Password);
17                 if (this.Proxy != null)
18                 {
19                     Request.Proxy = this.Proxy;
20                 }
21                 //封装文件传输协议FTP服务器对请求的响应
22                 FtpWebResponse ftpWebResp = (FtpWebResponse)Request.GetResponse();
23                 return ftpWebResp;
24             }
25             catch (Exception ep)
26             {
27                 ErrorMsg = ep.Message;
28                 return null;
29             }
30         }
View Code

FTP上传文件的方法

 1         #region FTP上传文件
 2 
 3         /// <summary>
 4         /// 读取上传到FTP服务器的文件,如存在,则上传
 5         /// </summary>
 6         /// <param name="localFullPath">本地带有完整路径的文件名</param>
 7         /// <param name="RemoteFileName">要在FTP服务器上保存的文件名</param>
 8         public bool UpLoadFile(string localFullPath, string RemoteFileName)
 9         {
10             try
11             {
12                 //如果上传文件存在
13                 if (File.Exists(localFullPath))
14                 {
15                     //将文件解析成流
16                     FileStream Stream = new FileStream(localFullPath, FileMode.Open, FileAccess.Read);
17                     byte[] bt = new byte[Stream.Length];
18                     Stream.Read(bt, 0, Convert.ToInt32(Stream.Length));
19                     Stream.Close();
20                     UpLoadFileMethod(bt, RemoteFileName);
21                     return true;
22                 }
23                 else
24                 {
25                     return false;
26                     throw new Exception("无法找到" + localFullPath);
27                 }
28             }
29             catch (Exception ep)
30             {
31                 ErrorMsg = ep.Message;
32                 return false;
33             }
34         }
35 
36         /// <summary>
37         /// 上传文件到FTP服务器
38         /// </summary>
39         /// <param name="FileBytes">文件二进制内容</param>
40         /// <param name="RemoteFileName">保存的文件名</param>
41         public void UpLoadFileMethod(byte[] FileBytes, string RemoteFileName)
42         {
43             try
44             {
45                 if (File.Exists(RemoteFileName))
46                 {
47                     throw new Exception("FTP存在相同文件!");
48                 }
49                 Response = OpenFTP(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.UploadFile);
50                 Stream requestStream = Request.GetRequestStream();
51                 //创建内存支持的流
52                 MemoryStream memoryStream = new MemoryStream(FileBytes);
53                 byte[] buffer = new byte[1024];
54                 int bytesRead = 0;
55                 int totalRead = 0;
56                 while (true)
57                 {
58                     //读取流,赋给buffer
59                     bytesRead = memoryStream.Read(buffer, 0, buffer.Length);
60                     if (bytesRead == 0)
61                     {
62                         break;
63                     }
64                     totalRead += bytesRead;
65                     requestStream.Write(buffer, 0, bytesRead);
66                 }
67                 requestStream.Close();
68                 Response = (FtpWebResponse)Request.GetResponse();
69                 memoryStream.Close();
70                 memoryStream.Dispose();
71                 FileBytes = null;
72             }
73             catch (Exception ep)
74             {
75                 ErrorMsg = ep.Message;
76             }
77         }
78 
79         #endregion
View Code

FTP下载文件的方法

 1 #region FTP下载文件
 2 
 3         /// <summary>
 4         /// 文件下载
 5         /// </summary>
 6         /// <param name="RemoteFileName">FTP文件名</param>
 7         /// <param name="LocalPath">保存本地的路径</param>
 8         /// <param name="LocalFileName">保存本地的文件名</param>
 9         /// <returns>是否下载完成</returns>
10         public bool DownLoadFile(string RemoteFileName, string LocalPath, string LocalFileName)
11         {
12             byte[] bt = null;
13             try
14             {
15                 if (!Directory.Exists(LocalPath))
16                 {
17                     throw new Exception("无法找到" + LocalPath);
18                 }
19                 string LocalFullPath = Path.Combine(LocalPath, LocalFileName);
20                 bt = DownLoadFileMethod(RemoteFileName);
21                 if (bt != null)
22                 {
23                     FileStream fileStr = new FileStream(LocalFullPath, FileMode.Create);
24                     fileStr.Write(bt, 0, bt.Length);
25                     fileStr.Flush();
26                     fileStr.Close();
27                     return true;
28                 }
29                 else
30                 {
31                     return false;
32                 }
33             }
34             catch (Exception ep)
35             {
36                 ErrorMsg = ep.Message;
37                 return false;
38             }
39         }
40 
41         /// <summary>
42         /// 文件下载
43         /// </summary>
44         /// <param name="RemoteFileName">FTP文件名</param>
45         /// <returns>文件流</returns>
46         public byte[] DownLoadFileMethod(string RemoteFileName)
47         {
48             try
49             {
50                 Response = OpenFTP(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.DownloadFile);
51                 Stream Reader = Response.GetResponseStream();
52                 MemoryStream memoryStr = new MemoryStream(1024 * 500);
53                 byte[] buffer = new byte[1024];
54                 int bytesRead = 0;
55                 int TotalByteRead = 0;
56                 while (true)
57                 {
58                     bytesRead = Reader.Read(buffer, 0, buffer.Length);
59                     TotalByteRead += bytesRead;
60                     if (bytesRead == 0)
61                     {
62                         break;
63                     }
64                     memoryStr.Write(buffer, 0, bytesRead);
65                 }
66                 if (memoryStr.Length > 0)
67                 {
68                     return memoryStr.ToArray();
69                 }
70                 else
71                 {
72                     return null;
73                 }
74             }
75             catch (Exception ep)
76             {
77                 ErrorMsg = ep.Message;
78                 return null;
79             }
80         }
81         #endregion
View Code

获取FTP上文件目录的信息

  1         #region 列出目录文件信息
  2 
  3         /// <summary>
  4         /// 列出FTP服务器上当前目录的所有文件
  5         /// </summary>
  6         /// <returns></returns>
  7         public FileStruct[] ListFiles()
  8         {
  9             FileStruct[] listAll = ListFilesAndDirectories();
 10             List<FileStruct> listFile = new List<FileStruct>();
 11             foreach (FileStruct file in listAll)
 12             {
 13                 if (!file.IsDirectory)
 14                 {
 15                     listFile.Add(file);
 16                 }
 17             }
 18             return listFile.ToArray();
 19         }
 20 
 21         /// <summary>
 22         /// 获得文件和目录列表
 23         /// </summary>
 24         /// <param name="datastring">FTP返回的列表字符信息</param>
 25         public FileStruct[] GetList(string dataString)
 26         {
 27             List<FileStruct> myListArray = new List<FileStruct>();
 28             string[] dataRecords = dataString.Split('
');
 29             FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);
 30             foreach (string s in dataRecords)
 31             {
 32                 if (_directoryListStyle != FileListStyle.Unknown && !string.IsNullOrEmpty(s))
 33                 {
 34                     FileStruct f = new FileStruct();
 35                     f.Name = "..";
 36                     switch (_directoryListStyle)
 37                     {
 38                         case FileListStyle.UnixStyle:
 39                             f = ParseFileStructFromUnixStyleRecord(s);
 40                             break;
 41                         case FileListStyle.WindowsStyle:
 42                             f = ParseFileStructFromWindowsStyleRecord(s);
 43                             break;
 44                     }
 45                     if (!(f.Name == "." || f.Name == ".."))
 46                     {
 47                         myListArray.Add(f);
 48                     }
 49                 }
 50             }
 51             return myListArray.ToArray();
 52         }
 53 
 54         /// <summary>
 55         /// 列出FTP服务器上面当前目录的所有文件和目录
 56         /// </summary>
 57         public FileStruct[] ListFilesAndDirectories()
 58         {
 59             try
 60             {
 61                 Response = OpenFTP(this.Uri, WebRequestMethods.Ftp.ListDirectoryDetails);
 62                 if (Response == null)
 63                 {
 64                     ErrorMsg = "无法连接到FTP!";
 65                     return null;
 66                 }
 67                 StreamReader streamRea = new StreamReader(Response.GetResponseStream(), Encoding.Default);
 68                 string dataString = streamRea.ReadToEnd();
 69                 FileStruct[] list = GetList(dataString);
 70                 return list;
 71             }
 72             catch (Exception ep)
 73             {
 74                 ErrorMsg = ep.Message;
 75                 return null;
 76             }
 77         }
 78 
 79         /// <summary>
 80         /// 列出FTP服务器上面当前目录的所有的目录
 81         /// </summary>
 82         public FileStruct[] ListDirectories()
 83         {
 84             FileStruct[] listAll = ListFilesAndDirectories();
 85             List<FileStruct> listDirectory = new List<FileStruct>();
 86             foreach (FileStruct file in listAll)
 87             {
 88                 if (file.IsDirectory)
 89                 {
 90                     listDirectory.Add(file);
 91                 }
 92             }
 93             return listDirectory.ToArray();
 94         }
 95 
 96         /// <summary>
 97         /// 判断当前目录下指定的子目录是否存在
 98         /// </summary>
 99         /// <param name="RemoteDirectoryName">指定的目录名</param>
100         public bool DirectoryExist(string RemoteDirectoryName)
101         {
102             try
103             {
104                 FileStruct[] listDir = ListDirectories();
105                 foreach (FileStruct dir in listDir)
106                 {
107                     if (dir.Name == RemoteDirectoryName)
108                     {
109                         return true;
110                     }
111                 }
112                 return false;
113             }
114             catch (Exception ep)
115             {
116                 ErrorMsg = ep.Message;
117                 return false;
118             }
119         }
120 
121         /// <summary>
122         /// 新建Ftp文件夹
123         /// </summary>
124         /// <param name="DirectoryName">路径名</param>
125         /// <returns>是否新建成功</returns>
126         public bool MakeDirectory(string DirectoryName)
127         {
128             try
129             {
130                 Response = OpenFTP(new Uri(this.Uri.ToString() + DirectoryName), WebRequestMethods.Ftp.MakeDirectory);
131                 return true;
132             }
133             catch (Exception ep)
134             {
135                 ErrorMsg = ep.Message;
136                 return false;
137             }
138         }
139 
140         /// <summary>
141         /// 判断文件列表的方式是Window还是Unix
142         /// </summary>
143         /// <param name="recordList">文件信息列表</param>
144         /// <returns></returns>
145         private FileListStyle GuessFileListStyle(string[] recordList)
146         {
147             foreach (string s in recordList)
148             {
149                 if (s.Length > 10 && Regex.IsMatch(s.Substring(0, 10), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)"))
150                 {
151                     return FileListStyle.UnixStyle;
152                 }
153                 else if (s.Length > 8 && Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"))
154                 {
155                     return FileListStyle.WindowsStyle;
156                 }
157             }
158             return FileListStyle.Unknown;
159         }
160 
161         /// <summary>
162         /// 从Unix格式中返回文件信息
163         /// </summary>
164         /// <param name="Record">文件信息</param>
165         private FileStruct ParseFileStructFromUnixStyleRecord(string Record)
166         {
167             FileStruct f = new FileStruct();
168             string[] tempdata = Record.Split(' ');
169             try
170             {
171                 f.Size = int.Parse((IsNumeric(tempdata[tempdata.Length - 5]) ? tempdata[tempdata.Length - 5] : tempdata[tempdata.Length - 6]));
172             }
173             catch (Exception ex)
174             {
175                 string errs = ex.Message;
176                 f.Size = -1;
177             }
178 
179             string processstr = Record.Trim();
180             f.Flags = processstr.Substring(0, 10);
181             f.IsDirectory = (f.Flags[0] == 'd');
182             processstr = (processstr.Substring(11)).Trim();
183             _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
184             //跳过一部分
185             f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
186             f.Group = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
187             _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
188             //跳过一部分
189             string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2];
190             if (yearOrTime.IndexOf(":") >= 0)
191             {
192                 //time
193                 processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());
194             }
195             f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', 8));
196             f.Name = processstr;
197             //最后就是名称
198             return f;
199         }
200 
201         /// <summary>
202         /// 从Windows格式中返回文件信息
203         /// </summary>
204         /// <param name="Record">文件信息</param>
205 
206         private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)
207         {
208             FileStruct f = new FileStruct();
209             string processstr = Record.Trim();
210             string dateStr = processstr.Substring(0, 8);
211             processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();
212             string timeStr = processstr.Substring(0, 7);
213             processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();
214             DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;
215             myDTFI.ShortTimePattern = "t";
216             f.CreateTime = DateTime.Parse((dateStr + " ") + timeStr, myDTFI);
217             if (processstr.Substring(0, 5) == "<DIR>")
218             {
219                 f.IsDirectory = true;
220                 processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();
221             }
222             else
223             {
224                 string[] strs = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
225                 // true);
226                 processstr = strs[1];
227                 f.IsDirectory = false;
228             }
229             f.Name = processstr;
230             return f;
231         }
232 
233         /// <summary>
234         /// 是否是数字
235         /// </summary>
236         /// <param name="value"></param>
237         /// <returns></returns>
238         bool IsNumeric(string value)
239         {
240             try
241             {
242                 Int64.Parse(value);
243                 return true;
244             }
245             catch
246             {
247                 return false;
248             }
249         }
250 
251         /// <summary>
252         /// 按照一定的规则进行字符串截取
253         /// </summary>
254         /// <param name="s">截取的字符串</param>
255         /// <param name="c">查找的字符</param>
256         /// <param name="startIndex">查找的位置</param>
257 
258         private string _cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)
259         {
260             int pos1 = s.IndexOf(c, startIndex);
261             string retString = s.Substring(0, pos1);
262             s = (s.Substring(pos1)).Trim();
263             return retString;
264         }
265 
266         /// <summary>
267         /// 进入一个目录
268         /// </summary>
269         /// <param name="DirectoryName">
270         /// 新目录的名字。
271         /// 说明:如果新目录是当前目录的子目录,则直接指定子目录。如: SubDirectory1/SubDirectory2 ;
272         /// 如果新目录不是当前目录的子目录,则必须从根目录一级一级的指定。如: ./NewDirectory/SubDirectory1/SubDirectory2
273         /// </param>
274         public bool GotoDirectory(string DirectoryName)
275         {
276             string CurrentWorkPath = this.DirectoryPath;
277             try
278             {
279                 DirectoryName = DirectoryName.Replace("\", "/");
280                 string[] DirectoryNames = DirectoryName.Split(new char[] { '/' });
281                 if (DirectoryNames[0] == ".")
282                 {
283                     this.DirectoryPath = "/";
284                     if (DirectoryNames.Length == 1)
285                     {
286                         return true;
287                     }
288                     Array.Clear(DirectoryNames, 0, 1);
289                 }
290                 bool Success = false;
291                 foreach (string dir in DirectoryNames)
292                 {
293                     if (dir != null)
294                     {
295                         Success = EnterOneSubDirectory(dir);
296                         if (!Success)
297                         {
298                             this.DirectoryPath = CurrentWorkPath;
299                             return false;
300                         }
301                     }
302                 }
303 
304                 return Success;
305             }
306             catch (Exception ep)
307             {
308                 this.DirectoryPath = CurrentWorkPath;
309                 ErrorMsg = ep.Message;
310             }
311             return true;
312         }
313 
314         /// <summary>
315         /// 从当前工作目录进入一个子目录
316         /// </summary>
317         /// <param name="DirectoryName">子目录名称</param>
318         private bool EnterOneSubDirectory(string DirectoryName)
319         {
320             try
321             {
322                 if (DirectoryName.Length > 0 && DirectoryExist(DirectoryName))
323                 {
324                     if (!DirectoryName.EndsWith("/"))
325                     {
326                         DirectoryName += "/";
327                     }
328                     _DirectoryPath += DirectoryName;
329                     return true;
330                 }
331                 else
332                 {
333                     return false;
334                 }
335             }
336             catch (Exception ep)
337             {
338                 ErrorMsg = ep.Message;
339                 return false;
340             }
341         }
342 
343         #endregion
View Code

在FTP是删除文件

 1         #region 删除文件
 2 
 3         /// <summary>
 4         /// 从FTP服务器上删除一个文件
 5         /// </summary>
 6         /// <param name="RemoteFileName"></param>
 7         /// <returns></returns>
 8         public bool DeleteFile(string RemoteFileName)
 9         {
10             try
11             {
12                 RemoteFileName = RemoteFileName.Replace("//", "/");
13                 Response = OpenFTP(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.DeleteFile);
14                 return true;
15             }
16             catch (Exception ex)
17             {
18                 ErrorMsg = ex.Message;
19                 return false;
20             }
21         }
22 
23         #endregion
View Code

构造,赋值

 1         #region Initialization and Cleanup
 2 
 3         /// <summary>
 4         /// 构造函数
 5         /// </summary>
 6         /// <param name="FtpUri">FTP地址</param>
 7         /// <param name="strUserName">登录用户名</param>
 8         /// <param name="strPassword">登录密码</param>
 9         public FtpAgent(Uri FtpUri, string strUserName, string strPassword)
10         {
11             this._Uri = new Uri(FtpUri.GetLeftPart(UriPartial.Authority));
12             _DirectoryPath = FtpUri.AbsolutePath;
13             if (!_DirectoryPath.EndsWith("/"))
14             {
15                 _DirectoryPath += "/";
16             }
17             this._UserName = strUserName;
18             this._Password = strPassword;
19             this._Proxy = null;
20         }
21 
22         /// <summary>
23         /// 构造函数
24         /// </summary>
25         public FtpAgent()
26         {
27             this._UserName = "anonymous";
28             //匿名用户
29             this._Password = "@anonymous";
30             this._Uri = null;
31             this._Proxy = null;
32         }
33 
34         #endregion
View Code

文件上传(WPF)

定义FTP的用户名,密码和地址

1 private string userName = "";
2 private string passwordStr = "";
3 private string ftpPathUrl = "";

文件上传的方法,参数,多个文件路径

 1 private void UploadFile(string[] filePaths)
 2         {
 3             FtpAgent ftp = new FtpAgent();
 4             //用户名
 5             ftp.UserName = userName;
 6             //用户密码
 7             ftp.Password = passwordStr;
 8             //ftp地址
 9             string uploadFilrUrl = ftpPathUrl;
10             //路径
11             ftp.Uri = new Uri("ftp://" + uploadFilrUrl);
12             //test路径
13             string testDir = "Test";
14             //判断文件夹是否存在,不存在则新建
15             if (!ftp.DirectoryExist(testDir))
16             {
17                 ftp.MakeDirectory(testDir);
18             }
19             ftp.GotoDirectory(testDir);
20 
21             for (int i = 0; i < filePaths.Count(); i++)
22             {
23                 string tempPath = filePaths[i];
24                 string tempName = System.IO.Path.GetFileNameWithoutExtension(tempPath);
25 
26                 ftp.UpLoadFile(tempPath, tempName);
27             }
28         }
View Code

单个文件上传的事件

 1         private void Button_Click(object sender, RoutedEventArgs e)
 2         {
 3             OpenFileDialog selectedFileDialog = new OpenFileDialog();
 4             selectedFileDialog.Title = "上传";
 5             selectedFileDialog.AddExtension = true;
 6             selectedFileDialog.FilterIndex = 1;
 7             selectedFileDialog.Multiselect = false;
 8             if (selectedFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
 9             {
10                 string path = selectedFileDialog.FileName;
11                 singleFileText.Text = System.IO.Path.GetFileName(path);
12                 string[] filePath = {path};
13                 UploadFile(filePath);
14             }
15         }
View Code

多个文件上传的事件

 1         private void Button_Click_1(object sender, RoutedEventArgs e)
 2         {
 3             OpenFileDialog selectedFileDialog = new OpenFileDialog();
 4             selectedFileDialog.Title = "上传";
 5             selectedFileDialog.AddExtension = true;
 6             selectedFileDialog.FilterIndex = 1;
 7             selectedFileDialog.Multiselect = true;
 8             if (selectedFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
 9             {
10                 var paths = selectedFileDialog.FileNames;
11                 string path = "";
12                 foreach (var tempPath in paths)
13                 {
14                     path += System.IO.Path.GetFileName(tempPath) + ";";
15                 }
16                 mulFileText.Text = path;
17                 UploadFile(paths);
18             }
19         }
View Code

固定格式文件的上传事件

 1         private void Button_Click_2(object sender, RoutedEventArgs e)
 2         {
 3             OpenFileDialog selectedFileDialog = new OpenFileDialog();
 4             selectedFileDialog.Title = "上传";
 5             selectedFileDialog.AddExtension = true;
 6             selectedFileDialog.FilterIndex = 1;
 7             selectedFileDialog.Filter = "Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx";
 8             selectedFileDialog.Multiselect = false;
 9             if (selectedFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
10             {
11                 string path = selectedFileDialog.FileName;
12                 excelFileText.Text = System.IO.Path.GetFileName(path);
13                 string[] filePath = { path };
14                 UploadFile(filePath);
15             }
16         }
View Code

文件下载(WPF)

 1         private void Button_Click_3(object sender, RoutedEventArgs e)
 2         {
 3             FtpAgent ftp = new FtpAgent();
 4             //用户名
 5             ftp.UserName = userName;
 6             //用户密码
 7             ftp.Password = passwordStr;
 8             //ftp地址
 9             string uploadFilrUrl = ftpPathUrl;
10             //test文件夹
11             ftp.Uri = new Uri("ftp://" + uploadFilrUrl);
12 
13             System.Windows.Forms.FolderBrowserDialog folder = new System.Windows.Forms.FolderBrowserDialog();
14             if (folder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
15             {
16                 ftp.GotoDirectory("Test");
17                 string localSavePath = folder.SelectedPath;
18                 bool isSuccess = ftp.DownLoadFile("Test.txt", localSavePath, "Test.txt");
19                 if (isSuccess)
20                 {
21                     System.Windows.MessageBox.Show("下载成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
22                 }
23             }
24         }
View Code

结束

  刚发现,还有好几个草稿,就先把这个写完,MVC的授权和路由还在研究中~

原文地址:https://www.cnblogs.com/shadow-fei/p/4639516.html