一、C#实现本地文件下载
1、文件下载的路径 文件名称 以及文件下载之后要放的位置 这三个变量是必须要的
2、定义以下四个对象:
FileWebRequest ftpWebRequest = null; FileWebResponse ftpWebResponse = null; Stream ftpResponseStream = null; FileStream outputStream = null;
3、创建文件下载存放位置的路径(不需要手动创建,如果路径存在就创建 不存在就不创建)
Directory.CreateDirectory(LocalFolder);//创建文件夹名称
* 这里提一点 Path.Combine()这个就是文件路径拼接的函数,会自动判断,在需要的文件加 \
比如 string filePath= Path.Combine(“D:”,“test”,"download"); // filePath="D:\testdownload";
4、 然后执行以下代码 即可完成文件下载
ftpWebRequest = (FileWebRequest)FileWebRequest.Create(new Uri(uri)); ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpWebResponse = (FileWebResponse)ftpWebRequest.GetResponse(); ftpResponseStream = ftpWebResponse.GetResponseStream(); long contentLength = ftpWebResponse.ContentLength; int bufferSize = 2048; byte[] buffer = new byte[bufferSize]; int readCount; readCount = ftpResponseStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpResponseStream.Read(buffer, 0, bufferSize); }
5、代码写完之后要思考,下载文件的时候如何出现异常 这时在整个代码加个 Try{} catch{}
具体代码如下:
public static void Main(string[] args) { TestFile tf = new TestFile(); tf.fileDownload("D:/testFile/", "下载ftp文件.txt", "C:/Users/17/Desktop/文件", "下载ftp文件.txt", DateTime.Now.ToShortDateString()); } /// <summary> /// 下载文件 /// </summary> /// <param name="localPath">本地文件地址(没有文件名)</param> /// <param name="localFileName">本地文件名</param> /// <param name="ftpPath">下载的ftp的路径</param> /// <param name="ftpFileName">下载的ftp的文件名</param> public bool fileDownload(string localPath, string localFileName, string ftpPath, string ftpFileName, string date) { bool success = false; //FtpWebResponse ftpWebResponse = null; FileWebRequest ftpWebRequest = null; FileWebResponse ftpWebResponse = null; Stream ftpResponseStream = null; FileStream outputStream = null; try { //string date = DateTime.Now.ToShortDateString().ToString();//获取系统时间 string date1 = date.Replace("/", "");//winods 中文件命名不能有 / 去掉指定字符串 / //localPath = localPath + date1 + "/";//拼接路径 localPath=Path.Combine(localPath,date1) Directory.CreateDirectory(localPath);//创建文件夹名称 outputStream = new FileStream(localPath + localFileName, FileMode.Create);//创建文件 string uri = ftpRootURL + ftpPath + "/" + ftpFileName;//拼接目标文件路径 string uri= Path.Combine(ftpRootURL,ftpPath,ftpFileName); ftpWebRequest = (FileWebRequest)FileWebRequest.Create(new Uri(uri)); //ftpWebRequest1.UseBinary = true; ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpWebResponse = (FileWebResponse)ftpWebRequest.GetResponse(); ftpResponseStream = ftpWebResponse.GetResponseStream(); long contentLength = ftpWebResponse.ContentLength; int bufferSize = 2048; byte[] buffer = new byte[bufferSize]; int readCount; readCount = ftpResponseStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpResponseStream.Read(buffer, 0, bufferSize); } success = true; } catch (Exception e) { DirectoryInfo folder = new DirectoryInfo(localPath); StreamWriter log = new StreamWriter(localPath + "/" + DateTime.Now.ToShortDateString().ToString().Replace("/", "") + ".txt", true); log.WriteLine("发生异常时间:" + System.DateTime.Now.ToShortTimeString().ToString()); log.WriteLine("发生异常信息:" + e.Message); log.WriteLine("发送异常对象:" + e.Source); log.WriteLine("调用堆栈:" + e.StackTrace.Trim()); log.WriteLine("触动方法:" + e.TargetSite); log.WriteLine(" " + e.HResult); log.WriteLine("数据对象" + e.Data); log.WriteLine("____________________________________________________________"); log.WriteLine(); log.Close(); success = false; } finally { if (outputStream != null) { outputStream.Close(); } if (ftpResponseStream != null) { ftpResponseStream.Close(); } if (ftpWebResponse != null) { ftpWebResponse.Close(); } } return success; }
二、 FTP 服务文件下载
这个功能其实和本地文件下载一样,只需要加几点即可
1、FTP服务的地址;
具体代码如下
private string ftpIP = "**********";
2、FTP文件服务的登录账号以及密码
具体代码如下
private string ftpName = "*********"; private string ftpPassword = "******"; private string ftpRootURL = string.Empty; FtpWebRequest reqFTP;
3、获取FTP服务上的文件名称、FTP文件服务需要下载之后存放的路径以及下载功能的实现
FtpWebRequest ftpWebRequest = null; FtpWebResponse ftpWebResponse = null; Stream ftpResponseStream = null; FileStream outputStream = null; try { localFilePath = Path.Combine(localFilePath, ftpFileNameTime); Directory.CreateDirectory(localFilePath);//创建文件夹名称 outputStream = new FileStream(Path.Combine(localFilePath, fileName), FileMode.Create); string uri = Path.Combine(ftpRootURL, ftpIP, fileName); ftpWebRequest = (FtpWebRequest)FileWebRequest.Create(new Uri(uri)); ftpWebRequest.Credentials = new NetworkCredential(ftpName, ftpPassword);//登录ftp ftpWebRequest.UseBinary = true; ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); ftpResponseStream = ftpWebResponse.GetResponseStream(); long contentLength = ftpWebResponse.ContentLength; int bufferSize = 2048; byte[] buffer = new byte[bufferSize]; int readCount; readCount = ftpResponseStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpResponseStream.Read(buffer, 0, bufferSize); } } catch (Exception ex) { MessageBox.Show(ex.Message) /*MessageBox.Show(ex.Message + "是否下载日志文件", "发送错误!", MessageBoxButtons.OKCancel); //点击确定 就执行下载日志文件,不然就不执行 if (dr == DialogResult.OK) { WriteLog log = new WriteLog(); log.Write_log(ex.Message); }*/ } finally { if (outputStream != null) { outputStream.Close(); } if (ftpResponseStream != null) { ftpResponseStream.Close(); } if (ftpWebResponse != null) { ftpWebResponse.Close(); } }
5、具体代码如下:
namespace FtpDownLoad { public class ftpFileDownload { private string ftpIP = "*************"; private string ftpName = "2*******"; private string ftpPassword = "*********"; private string ftpRootURL = string.Empty; FtpWebRequest reqFTP; public static void Main(string[] args) { ftpFileDownload ftpDown = new ftpFileDownload(); ftpDown.GetFileList("D: estFile","37.pdt","20190703"); } /// <summary> /// 文件下载 /// </summary> /// <param name="localFilePath">下载路径</param> /// <param name="fileName">下载的名称</param> /// <param name="ftpFilePath">FTP路径</param> /// <param name="ftpFileNameTime">FTP文件的修改时间</param> public void FtpDownLoadFile(string localFilePath, string fileName, string ftpFileNameTime) { FtpWebRequest ftpWebRequest = null; FtpWebResponse ftpWebResponse = null; Stream ftpResponseStream = null; FileStream outputStream = null; try { localFilePath = Path.Combine(localFilePath, ftpFileNameTime); Directory.CreateDirectory(localFilePath);//创建文件夹名称 outputStream = new FileStream(Path.Combine(localFilePath, fileName), FileMode.Create); string uri = Path.Combine(ftpRootURL, ftpIP, fileName); ftpWebRequest = (FtpWebRequest)FileWebRequest.Create(new Uri(uri)); ftpWebRequest.Credentials = new NetworkCredential(ftpName, ftpPassword);//登录ftp ftpWebRequest.UseBinary = true; ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); ftpResponseStream = ftpWebResponse.GetResponseStream(); long contentLength = ftpWebResponse.ContentLength; int bufferSize = 2048; byte[] buffer = new byte[bufferSize]; int readCount; readCount = ftpResponseStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpResponseStream.Read(buffer, 0, bufferSize); } } catch (Exception ex) { MessageBox.Show(ex.Message); /* DialogResult dr = MessageBox.Show(ex.Message + "是否下载日志文件", "发送错误!", MessageBoxButtons.OKCancel); //点击确定 就执行下载日志文件,不然就不执行 if (dr == DialogResult.OK) { WriteLog log = new WriteLog(); log.Write_log(ex.Message); }*/ } finally { if (outputStream != null) { outputStream.Close(); } if (ftpResponseStream != null) { ftpResponseStream.Close(); } if (ftpWebResponse != null) { ftpWebResponse.Close(); } } }
如有疑问 可以往773408602@qq.com发邮件,我会第一时间给你解答的