接到一个任务,该任务需要从数据支持部的FTP上下载4个文件。
数据支持部的同事给了4个工具分别用下来载这4个文件
因为每天要定时下载,所以加入了计划任务。
这样一来,本可以做为一个任务来完成的东东却硬被分成了4个任务,
这还不是大问题,最大的问题是如果要下载的文件名规则有了变化,我就要分别改这4个工具的配置文件。
这4个工具虽能满足要求,但有点烦琐。看来还是不能偷懒了 - -
自己用FtpWebRequest来实现吧
下载文件
获取文件列表
上传文件
数据支持部的同事给了4个工具分别用下来载这4个文件
因为每天要定时下载,所以加入了计划任务。
这样一来,本可以做为一个任务来完成的东东却硬被分成了4个任务,
这还不是大问题,最大的问题是如果要下载的文件名规则有了变化,我就要分别改这4个工具的配置文件。
这4个工具虽能满足要求,但有点烦琐。看来还是不能偷懒了 - -
自己用FtpWebRequest来实现吧
下载文件
- /// <summary>
- /// 下载文件
- /// </summary>
- /// <param name="filename"></param>
- private static void DownLoadFile(string filename)
- {
- FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://" + FtpAddress + "/" + filename);
- req.Method = WebRequestMethods.Ftp.DownloadFile;
- req.UseBinary = true;
- req.UsePassive = true;
- req.Credentials = new NetworkCredential(FtpUid, FtpPwd);
- try
- {
- using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
- {
- string localfile = Path.Combine(LocalPath, filename);
- FileStream fs = new FileStream(localfile, FileMode.Create, FileAccess.Write);
- int buffer = 1024; //1K缓冲
- byte[] b = new byte[buffer];
- int i = 0;
- Stream stream = res.GetResponseStream();
- while ((i = stream.Read(b, 0, buffer)) > 0)
- {
- fs.Write(b, 0, i);
- }
- }
- Console.WriteLine(filename + " download!");
- Log(filename + "下载成功");
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- Log(ex.ToString());
- }
- finally
- {
- }
- }
获取文件列表
- /// <summary>
- /// 获取FTP文件列表
- /// </summary>
- /// <returns></returns>
- private static List<String> GetFileList()
- {
- List<string> list = new List<string>();
- FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + FtpAddress + FtpRemotePath));
- req.Credentials = new NetworkCredential(FtpUid, FtpPwd);
- req.Method = WebRequestMethods.Ftp.ListDirectory;
- req.UseBinary = true;
- req.UsePassive = true;
- try
- {
- using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
- {
- using (StreamReader sr = new StreamReader(res.GetResponseStream()))
- {
- string s;
- while ((s = sr.ReadLine()) != null)
- {
- list.Add(s);
- }
- }
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- Log("下载文件列表失败:");
- Log(ex.ToString());
- }
- return list;
- }
上传文件
- private static void UploadFile(string localFile)
- {
- FileInfo fi = new FileInfo(localFile);
- FileStream fs = fi.OpenRead();
- long length = fs.Length;
- FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://" + FtpAddress + FtpRemotePath + fi.Name);
- req.Credentials = new NetworkCredential(FtpUid, FtpPwd);
- req.Method = WebRequestMethods.Ftp.UploadFile;
- req.UseBinary = true;
- req.ContentLength = length;
- req.Timeout = 10 * 1000;
- try
- {
- Stream stream = req.GetRequestStream();
- int BufferLength = 2048; //2K
- byte[] b = new byte[BufferLength];
- int i;
- while ((i = fs.Read(b, 0, BufferLength)) > 0)
- {
- stream.Write(b, 0, i);
- }
- stream.Close();
- stream.Dispose();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- }
- }