C# FTP上传下载(支持断点续传)
- <pre class="csharp" name="code"><pre class="csharp" name="code">using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- using System.IO;
- namespace JianKunKing.Common.Ftp
- {
- /// <summary>
- /// ftp方式文件下载上传
- /// </summary>
- public static class FileUpDownload
- {
- #region 变量属性
- /// <summary>
- /// Ftp服务器ip
- /// </summary>
- public static string FtpServerIP = string.Empty;
- /// <summary>
- /// Ftp 指定用户名
- /// </summary>
- public static string FtpUserID = string.Empty;
- /// <summary>
- /// Ftp 指定用户密码
- /// </summary>
- public static string FtpPassword = string.Empty;
- #endregion
- #region 从FTP服务器下载文件,指定本地路径和本地文件名
- /// <summary>
- /// 从FTP服务器下载文件,指定本地路径和本地文件名
- /// </summary>
- /// <param name="remoteFileName">远程文件名</param>
- /// <param name="localFileName">保存本地的文件名(包含路径)</param>
- /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <returns>是否下载成功</returns>
- public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, Action<int, int> updateProgress = null)
- {
- FtpWebRequest reqFTP, ftpsize;
- Stream ftpStream = null;
- FtpWebResponse response = null;
- FileStream outputStream = null;
- try
- {
- outputStream = new FileStream(localFileName, FileMode.Create);
- if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
- {
- throw new Exception("ftp下载目标服务器地址未设置!");
- }
- Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
- ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
- ftpsize.UseBinary = true;
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.UseBinary = true;
- reqFTP.KeepAlive = false;
- if (ifCredential)//使用用户身份认证
- {
- ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- }
- ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
- FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
- long totalBytes = re.ContentLength;
- re.Close();
- reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
- response = (FtpWebResponse)reqFTP.GetResponse();
- ftpStream = response.GetResponseStream();
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)totalBytes, 0);//更新进度条
- }
- long totalDownloadedByte = 0;
- int bufferSize = 2048;
- int readCount;
- byte[] buffer = new byte[bufferSize];
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- while (readCount > 0)
- {
- totalDownloadedByte = readCount + totalDownloadedByte;
- outputStream.Write(buffer, 0, readCount);
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
- }
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- }
- ftpStream.Close();
- outputStream.Close();
- response.Close();
- return true;
- }
- catch (Exception)
- {
- return false;
- throw;
- }
- finally
- {
- if (ftpStream != null)
- {
- ftpStream.Close();
- }
- if (outputStream != null)
- {
- outputStream.Close();
- }
- if (response != null)
- {
- response.Close();
- }
- }
- }
- /// <summary>
- /// 从FTP服务器下载文件,指定本地路径和本地文件名(支持断点下载)
- /// </summary>
- /// <param name="remoteFileName">远程文件名</param>
- /// <param name="localFileName">保存本地的文件名(包含路径)</param>
- /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
- /// <param name="size">已下载文件流大小</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <returns>是否下载成功</returns>
- public static bool FtpBrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action<int, int> updateProgress = null)
- {
- FtpWebRequest reqFTP, ftpsize;
- Stream ftpStream = null;
- FtpWebResponse response = null;
- FileStream outputStream = null;
- try
- {
- outputStream = new FileStream(localFileName, FileMode.Append);
- if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
- {
- throw new Exception("ftp下载目标服务器地址未设置!");
- }
- Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
- ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
- ftpsize.UseBinary = true;
- ftpsize.ContentOffset = size;
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.UseBinary = true;
- reqFTP.KeepAlive = false;
- reqFTP.ContentOffset = size;
- if (ifCredential)//使用用户身份认证
- {
- ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- }
- ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
- FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
- long totalBytes = re.ContentLength;
- re.Close();
- reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
- response = (FtpWebResponse)reqFTP.GetResponse();
- ftpStream = response.GetResponseStream();
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)totalBytes, 0);//更新进度条
- }
- long totalDownloadedByte = 0;
- int bufferSize = 2048;
- int readCount;
- byte[] buffer = new byte[bufferSize];
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- while (readCount > 0)
- {
- totalDownloadedByte = readCount + totalDownloadedByte;
- outputStream.Write(buffer, 0, readCount);
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
- }
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- }
- ftpStream.Close();
- outputStream.Close();
- response.Close();
- return true;
- }
- catch (Exception)
- {
- return false;
- throw;
- }
- finally
- {
- if (ftpStream != null)
- {
- ftpStream.Close();
- }
- if (outputStream != null)
- {
- outputStream.Close();
- }
- if (response != null)
- {
- response.Close();
- }
- }
- }
- /// <summary>
- /// 从FTP服务器下载文件,指定本地路径和本地文件名
- /// </summary>
- /// <param name="remoteFileName">远程文件名</param>
- /// <param name="localFileName">保存本地的文件名(包含路径)</param>
- /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <param name="brokenOpen">是否断点下载:true 会在localFileName 找是否存在已经下载的文件,并计算文件流大小</param>
- /// <returns>是否下载成功</returns>
- public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, bool brokenOpen, Action<int, int> updateProgress = null)
- {
- if (brokenOpen)
- {
- try
- {
- long size = 0;
- if (File.Exists(localFileName))
- {
- using (FileStream outputStream = new FileStream(localFileName, FileMode.Open))
- {
- size = outputStream.Length;
- }
- }
- return FtpBrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);
- }
- catch
- {
- throw;
- }
- }
- else
- {
- return FtpDownload(remoteFileName, localFileName, ifCredential, updateProgress);
- }
- }
- #endregion
- #region 上传文件到FTP服务器
- /// <summary>
- /// 上传文件到FTP服务器
- /// </summary>
- /// <param name="localFullPath">本地带有完整路径的文件名</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <returns>是否下载成功</returns>
- public static bool FtpUploadFile(string localFullPathName, Action<int, int> updateProgress = null)
- {
- FtpWebRequest reqFTP;
- Stream stream = null;
- FtpWebResponse response = null;
- FileStream fs = null;
- try
- {
- FileInfo finfo = new FileInfo(localFullPathName);
- if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
- {
- throw new Exception("ftp上传目标服务器地址未设置!");
- }
- Uri uri = new Uri("ftp://" + FtpServerIP + "/" + finfo.Name);
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.KeepAlive = false;
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
- reqFTP.Method = WebRequestMethods.Ftp.UploadFile;//向服务器发出下载请求命令
- reqFTP.ContentLength = finfo.Length;//为request指定上传文件的大小
- response = reqFTP.GetResponse() as FtpWebResponse;
- reqFTP.ContentLength = finfo.Length;
- int buffLength = 1024;
- byte[] buff = new byte[buffLength];
- int contentLen;
- fs = finfo.OpenRead();
- stream = reqFTP.GetRequestStream();
- contentLen = fs.Read(buff, 0, buffLength);
- int allbye = (int)finfo.Length;
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)allbye, 0);//更新进度条
- }
- int startbye = 0;
- while (contentLen != 0)
- {
- startbye = contentLen + startbye;
- stream.Write(buff, 0, contentLen);
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)allbye, (int)startbye);//更新进度条
- }
- contentLen = fs.Read(buff, 0, buffLength);
- }
- stream.Close();
- fs.Close();
- response.Close();
- return true;
- }
- catch (Exception)
- {
- return false;
- throw;
- }
- finally
- {
- if (fs != null)
- {
- fs.Close();
- }
- if (stream != null)
- {
- stream.Close();
- }
- if (response != null)
- {
- response.Close();
- }
- }
- }
- /// <summary>
- /// 上传文件到FTP服务器(断点续传)
- /// </summary>
- /// <param name="localFullPath">本地文件全路径名称:C:\Users\JianKunKing\Desktop\IronPython脚本测试工具</param>
- /// <param name="remoteFilepath">远程文件所在文件夹路径</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <returns></returns>
- public static bool FtpUploadBroken(string localFullPath, string remoteFilepath, Action<int, int> updateProgress = null)
- {
- if (remoteFilepath == null)
- {
- remoteFilepath = "";
- }
- string newFileName = string.Empty;
- bool success = true;
- FileInfo fileInf = new FileInfo(localFullPath);
- long allbye = (long)fileInf.Length;
- if (fileInf.Name.IndexOf("#") == -1)
- {
- newFileName = RemoveSpaces(fileInf.Name);
- }
- else
- {
- newFileName = fileInf.Name.Replace("#", "#");
- newFileName = RemoveSpaces(newFileName);
- }
- long startfilesize = GetFileSize(newFileName, remoteFilepath);
- if (startfilesize >= allbye)
- {
- return false;
- }
- long startbye = startfilesize;
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)allbye, (int)startfilesize);//更新进度条
- }
- string uri;
- if (remoteFilepath.Length == 0)
- {
- uri = "ftp://" + FtpServerIP + "/" + newFileName;
- }
- else
- {
- uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + newFileName;
- }
- FtpWebRequest reqFTP;
- // 根据uri创建FtpWebRequest对象
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
- // ftp用户名和密码
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- // 默认为true,连接不会被关闭
- // 在一个命令之后被执行
- reqFTP.KeepAlive = false;
- // 指定执行什么命令
- reqFTP.Method = WebRequestMethods.Ftp.AppendFile;
- // 指定数据传输类型
- reqFTP.UseBinary = true;
- // 上传文件时通知服务器文件的大小
- reqFTP.ContentLength = fileInf.Length;
- int buffLength = 2048;// 缓冲大小设置为2kb
- byte[] buff = new byte[buffLength];
- // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
- FileStream fs = fileInf.OpenRead();
- Stream strm = null;
- try
- {
- // 把上传的文件写入流
- strm = reqFTP.GetRequestStream();
- // 每次读文件流的2kb
- fs.Seek(startfilesize, 0);
- int contentLen = fs.Read(buff, 0, buffLength);
- // 流内容没有结束
- while (contentLen != 0)
- {
- // 把内容从file stream 写入 upload stream
- strm.Write(buff, 0, contentLen);
- contentLen = fs.Read(buff, 0, buffLength);
- startbye += contentLen;
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)allbye, (int)startbye);//更新进度条
- }
- }
- // 关闭两个流
- strm.Close();
- fs.Close();
- }
- catch
- {
- success = false;
- throw;
- }
- finally
- {
- if (fs != null)
- {
- fs.Close();
- }
- if (strm != null)
- {
- strm.Close();
- }
- }
- return success;
- }
- /// <summary>
- /// 去除空格
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- private static string RemoveSpaces(string str)
- {
- string a = "";
- CharEnumerator CEnumerator = str.GetEnumerator();
- while (CEnumerator.MoveNext())
- {
- byte[] array = new byte[1];
- array = System.Text.Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());
- int asciicode = (short)(array[0]);
- if (asciicode != 32)
- {
- a += CEnumerator.Current.ToString();
- }
- }
- string sdate = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString()
- + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString();
- return a.Split('.')[a.Split('.').Length - 2] + "." + a.Split('.')[a.Split('.').Length - 1];
- }
- /// <summary>
- /// 获取已上传文件大小
- /// </summary>
- /// <param name="filename">文件名称</param>
- /// <param name="path">服务器文件路径</param>
- /// <returns></returns>
- public static long GetFileSize(string filename, string remoteFilepath)
- {
- long filesize = 0;
- try
- {
- FtpWebRequest reqFTP;
- FileInfo fi = new FileInfo(filename);
- string uri;
- if (remoteFilepath.Length == 0)
- {
- uri = "ftp://" + FtpServerIP + "/" + fi.Name;
- }
- else
- {
- uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + fi.Name;
- }
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.KeepAlive = false;
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
- reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- filesize = response.ContentLength;
- return filesize;
- }
- catch
- {
- return 0;
- }
- }
- //public void Connect(String path, string ftpUserID, string ftpPassword)//连接ftp
- //{
- // // 根据uri创建FtpWebRequest对象
- // reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
- // // 指定数据传输类型
- // reqFTP.UseBinary = true;
- // // ftp用户名和密码
- // reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
- //}
- #endregion
- }
- }</pre><br></pre>
- <pre class="csharp" name="code">using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- using System.IO;
- namespace JianKunKing.Common.Ftp
- {
- /// <summary>
- /// ftp方式文件下载上传
- /// </summary>
- public static class FileUpDownload
- {
- #region 变量属性
- /// <summary>
- /// Ftp服务器ip
- /// </summary>
- public static string FtpServerIP = string.Empty;
- /// <summary>
- /// Ftp 指定用户名
- /// </summary>
- public static string FtpUserID = string.Empty;
- /// <summary>
- /// Ftp 指定用户密码
- /// </summary>
- public static string FtpPassword = string.Empty;
- #endregion
- #region 从FTP服务器下载文件,指定本地路径和本地文件名
- /// <summary>
- /// 从FTP服务器下载文件,指定本地路径和本地文件名
- /// </summary>
- /// <param name="remoteFileName">远程文件名</param>
- /// <param name="localFileName">保存本地的文件名(包含路径)</param>
- /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <returns>是否下载成功</returns>
- public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, Action<int, int> updateProgress = null)
- {
- FtpWebRequest reqFTP, ftpsize;
- Stream ftpStream = null;
- FtpWebResponse response = null;
- FileStream outputStream = null;
- try
- {
- outputStream = new FileStream(localFileName, FileMode.Create);
- if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
- {
- throw new Exception("ftp下载目标服务器地址未设置!");
- }
- Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
- ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
- ftpsize.UseBinary = true;
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.UseBinary = true;
- reqFTP.KeepAlive = false;
- if (ifCredential)//使用用户身份认证
- {
- ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- }
- ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
- FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
- long totalBytes = re.ContentLength;
- re.Close();
- reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
- response = (FtpWebResponse)reqFTP.GetResponse();
- ftpStream = response.GetResponseStream();
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)totalBytes, 0);//更新进度条
- }
- long totalDownloadedByte = 0;
- int bufferSize = 2048;
- int readCount;
- byte[] buffer = new byte[bufferSize];
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- while (readCount > 0)
- {
- totalDownloadedByte = readCount + totalDownloadedByte;
- outputStream.Write(buffer, 0, readCount);
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
- }
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- }
- ftpStream.Close();
- outputStream.Close();
- response.Close();
- return true;
- }
- catch (Exception)
- {
- return false;
- throw;
- }
- finally
- {
- if (ftpStream != null)
- {
- ftpStream.Close();
- }
- if (outputStream != null)
- {
- outputStream.Close();
- }
- if (response != null)
- {
- response.Close();
- }
- }
- }
- /// <summary>
- /// 从FTP服务器下载文件,指定本地路径和本地文件名(支持断点下载)
- /// </summary>
- /// <param name="remoteFileName">远程文件名</param>
- /// <param name="localFileName">保存本地的文件名(包含路径)</param>
- /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
- /// <param name="size">已下载文件流大小</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <returns>是否下载成功</returns>
- public static bool FtpBrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action<int, int> updateProgress = null)
- {
- FtpWebRequest reqFTP, ftpsize;
- Stream ftpStream = null;
- FtpWebResponse response = null;
- FileStream outputStream = null;
- try
- {
- outputStream = new FileStream(localFileName, FileMode.Append);
- if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
- {
- throw new Exception("ftp下载目标服务器地址未设置!");
- }
- Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
- ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
- ftpsize.UseBinary = true;
- ftpsize.ContentOffset = size;
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.UseBinary = true;
- reqFTP.KeepAlive = false;
- reqFTP.ContentOffset = size;
- if (ifCredential)//使用用户身份认证
- {
- ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- }
- ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
- FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
- long totalBytes = re.ContentLength;
- re.Close();
- reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
- response = (FtpWebResponse)reqFTP.GetResponse();
- ftpStream = response.GetResponseStream();
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)totalBytes, 0);//更新进度条
- }
- long totalDownloadedByte = 0;
- int bufferSize = 2048;
- int readCount;
- byte[] buffer = new byte[bufferSize];
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- while (readCount > 0)
- {
- totalDownloadedByte = readCount + totalDownloadedByte;
- outputStream.Write(buffer, 0, readCount);
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
- }
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- }
- ftpStream.Close();
- outputStream.Close();
- response.Close();
- return true;
- }
- catch (Exception)
- {
- return false;
- throw;
- }
- finally
- {
- if (ftpStream != null)
- {
- ftpStream.Close();
- }
- if (outputStream != null)
- {
- outputStream.Close();
- }
- if (response != null)
- {
- response.Close();
- }
- }
- }
- /// <summary>
- /// 从FTP服务器下载文件,指定本地路径和本地文件名
- /// </summary>
- /// <param name="remoteFileName">远程文件名</param>
- /// <param name="localFileName">保存本地的文件名(包含路径)</param>
- /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <param name="brokenOpen">是否断点下载:true 会在localFileName 找是否存在已经下载的文件,并计算文件流大小</param>
- /// <returns>是否下载成功</returns>
- public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, bool brokenOpen, Action<int, int> updateProgress = null)
- {
- if (brokenOpen)
- {
- try
- {
- long size = 0;
- if (File.Exists(localFileName))
- {
- using (FileStream outputStream = new FileStream(localFileName, FileMode.Open))
- {
- size = outputStream.Length;
- }
- }
- return FtpBrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);
- }
- catch
- {
- throw;
- }
- }
- else
- {
- return FtpDownload(remoteFileName, localFileName, ifCredential, updateProgress);
- }
- }
- #endregion
- #region 上传文件到FTP服务器
- /// <summary>
- /// 上传文件到FTP服务器
- /// </summary>
- /// <param name="localFullPath">本地带有完整路径的文件名</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <returns>是否下载成功</returns>
- public static bool FtpUploadFile(string localFullPathName, Action<int, int> updateProgress = null)
- {
- FtpWebRequest reqFTP;
- Stream stream = null;
- FtpWebResponse response = null;
- FileStream fs = null;
- try
- {
- FileInfo finfo = new FileInfo(localFullPathName);
- if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
- {
- throw new Exception("ftp上传目标服务器地址未设置!");
- }
- Uri uri = new Uri("ftp://" + FtpServerIP + "/" + finfo.Name);
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.KeepAlive = false;
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
- reqFTP.Method = WebRequestMethods.Ftp.UploadFile;//向服务器发出下载请求命令
- reqFTP.ContentLength = finfo.Length;//为request指定上传文件的大小
- response = reqFTP.GetResponse() as FtpWebResponse;
- reqFTP.ContentLength = finfo.Length;
- int buffLength = 1024;
- byte[] buff = new byte[buffLength];
- int contentLen;
- fs = finfo.OpenRead();
- stream = reqFTP.GetRequestStream();
- contentLen = fs.Read(buff, 0, buffLength);
- int allbye = (int)finfo.Length;
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)allbye, 0);//更新进度条
- }
- int startbye = 0;
- while (contentLen != 0)
- {
- startbye = contentLen + startbye;
- stream.Write(buff, 0, contentLen);
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)allbye, (int)startbye);//更新进度条
- }
- contentLen = fs.Read(buff, 0, buffLength);
- }
- stream.Close();
- fs.Close();
- response.Close();
- return true;
- }
- catch (Exception)
- {
- return false;
- throw;
- }
- finally
- {
- if (fs != null)
- {
- fs.Close();
- }
- if (stream != null)
- {
- stream.Close();
- }
- if (response != null)
- {
- response.Close();
- }
- }
- }
- /// <summary>
- /// 上传文件到FTP服务器(断点续传)
- /// </summary>
- /// <param name="localFullPath">本地文件全路径名称:C:\Users\JianKunKing\Desktop\IronPython脚本测试工具</param>
- /// <param name="remoteFilepath">远程文件所在文件夹路径</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <returns></returns>
- public static bool FtpUploadBroken(string localFullPath, string remoteFilepath, Action<int, int> updateProgress = null)
- {
- if (remoteFilepath == null)
- {
- remoteFilepath = "";
- }
- string newFileName = string.Empty;
- bool success = true;
- FileInfo fileInf = new FileInfo(localFullPath);
- long allbye = (long)fileInf.Length;
- if (fileInf.Name.IndexOf("#") == -1)
- {
- newFileName = RemoveSpaces(fileInf.Name);
- }
- else
- {
- newFileName = fileInf.Name.Replace("#", "#");
- newFileName = RemoveSpaces(newFileName);
- }
- long startfilesize = GetFileSize(newFileName, remoteFilepath);
- if (startfilesize >= allbye)
- {
- return false;
- }
- long startbye = startfilesize;
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)allbye, (int)startfilesize);//更新进度条
- }
- string uri;
- if (remoteFilepath.Length == 0)
- {
- uri = "ftp://" + FtpServerIP + "/" + newFileName;
- }
- else
- {
- uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + newFileName;
- }
- FtpWebRequest reqFTP;
- // 根据uri创建FtpWebRequest对象
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
- // ftp用户名和密码
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- // 默认为true,连接不会被关闭
- // 在一个命令之后被执行
- reqFTP.KeepAlive = false;
- // 指定执行什么命令
- reqFTP.Method = WebRequestMethods.Ftp.AppendFile;
- // 指定数据传输类型
- reqFTP.UseBinary = true;
- // 上传文件时通知服务器文件的大小
- reqFTP.ContentLength = fileInf.Length;
- int buffLength = 2048;// 缓冲大小设置为2kb
- byte[] buff = new byte[buffLength];
- // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
- FileStream fs = fileInf.OpenRead();
- Stream strm = null;
- try
- {
- // 把上传的文件写入流
- strm = reqFTP.GetRequestStream();
- // 每次读文件流的2kb
- fs.Seek(startfilesize, 0);
- int contentLen = fs.Read(buff, 0, buffLength);
- // 流内容没有结束
- while (contentLen != 0)
- {
- // 把内容从file stream 写入 upload stream
- strm.Write(buff, 0, contentLen);
- contentLen = fs.Read(buff, 0, buffLength);
- startbye += contentLen;
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)allbye, (int)startbye);//更新进度条
- }
- }
- // 关闭两个流
- strm.Close();
- fs.Close();
- }
- catch
- {
- success = false;
- throw;
- }
- finally
- {
- if (fs != null)
- {
- fs.Close();
- }
- if (strm != null)
- {
- strm.Close();
- }
- }
- return success;
- }
- /// <summary>
- /// 去除空格
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- private static string RemoveSpaces(string str)
- {
- string a = "";
- CharEnumerator CEnumerator = str.GetEnumerator();
- while (CEnumerator.MoveNext())
- {
- byte[] array = new byte[1];
- array = System.Text.Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());
- int asciicode = (short)(array[0]);
- if (asciicode != 32)
- {
- a += CEnumerator.Current.ToString();
- }
- }
- string sdate = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString()
- + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString();
- return a.Split('.')[a.Split('.').Length - 2] + "." + a.Split('.')[a.Split('.').Length - 1];
- }
- /// <summary>
- /// 获取已上传文件大小
- /// </summary>
- /// <param name="filename">文件名称</param>
- /// <param name="path">服务器文件路径</param>
- /// <returns></returns>
- public static long GetFileSize(string filename, string remoteFilepath)
- {
- long filesize = 0;
- try
- {
- FtpWebRequest reqFTP;
- FileInfo fi = new FileInfo(filename);
- string uri;
- if (remoteFilepath.Length == 0)
- {
- uri = "ftp://" + FtpServerIP + "/" + fi.Name;
- }
- else
- {
- uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + fi.Name;
- }
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.KeepAlive = false;
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
- reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- filesize = response.ContentLength;
- return filesize;
- }
- catch
- {
- return 0;
- }
- }
- //public void Connect(String path, string ftpUserID, string ftpPassword)//连接ftp
- //{
- // // 根据uri创建FtpWebRequest对象
- // reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
- // // 指定数据传输类型
- // reqFTP.UseBinary = true;
- // // ftp用户名和密码
- // reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
- //}
- #endregion
- }
- }</pre><br>
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- using System.IO;
- namespace JianKunKing.Common.Ftp
- {
- /// <summary>
- /// ftp方式文件下载上传
- /// </summary>
- public static class FileUpDownload
- {
- #region 变量属性
- /// <summary>
- /// Ftp服务器ip
- /// </summary>
- public static string FtpServerIP = string.Empty;
- /// <summary>
- /// Ftp 指定用户名
- /// </summary>
- public static string FtpUserID = string.Empty;
- /// <summary>
- /// Ftp 指定用户密码
- /// </summary>
- public static string FtpPassword = string.Empty;
- #endregion
- #region 从FTP服务器下载文件,指定本地路径和本地文件名
- /// <summary>
- /// 从FTP服务器下载文件,指定本地路径和本地文件名
- /// </summary>
- /// <param name="remoteFileName">远程文件名</param>
- /// <param name="localFileName">保存本地的文件名(包含路径)</param>
- /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <returns>是否下载成功</returns>
- public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, Action<int, int> updateProgress = null)
- {
- FtpWebRequest reqFTP, ftpsize;
- Stream ftpStream = null;
- FtpWebResponse response = null;
- FileStream outputStream = null;
- try
- {
- outputStream = new FileStream(localFileName, FileMode.Create);
- if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
- {
- throw new Exception("ftp下载目标服务器地址未设置!");
- }
- Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
- ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
- ftpsize.UseBinary = true;
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.UseBinary = true;
- reqFTP.KeepAlive = false;
- if (ifCredential)//使用用户身份认证
- {
- ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- }
- ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
- FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
- long totalBytes = re.ContentLength;
- re.Close();
- reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
- response = (FtpWebResponse)reqFTP.GetResponse();
- ftpStream = response.GetResponseStream();
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)totalBytes, 0);//更新进度条
- }
- long totalDownloadedByte = 0;
- int bufferSize = 2048;
- int readCount;
- byte[] buffer = new byte[bufferSize];
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- while (readCount > 0)
- {
- totalDownloadedByte = readCount + totalDownloadedByte;
- outputStream.Write(buffer, 0, readCount);
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
- }
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- }
- ftpStream.Close();
- outputStream.Close();
- response.Close();
- return true;
- }
- catch (Exception)
- {
- return false;
- throw;
- }
- finally
- {
- if (ftpStream != null)
- {
- ftpStream.Close();
- }
- if (outputStream != null)
- {
- outputStream.Close();
- }
- if (response != null)
- {
- response.Close();
- }
- }
- }
- /// <summary>
- /// 从FTP服务器下载文件,指定本地路径和本地文件名(支持断点下载)
- /// </summary>
- /// <param name="remoteFileName">远程文件名</param>
- /// <param name="localFileName">保存本地的文件名(包含路径)</param>
- /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
- /// <param name="size">已下载文件流大小</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <returns>是否下载成功</returns>
- public static bool FtpBrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action<int, int> updateProgress = null)
- {
- FtpWebRequest reqFTP, ftpsize;
- Stream ftpStream = null;
- FtpWebResponse response = null;
- FileStream outputStream = null;
- try
- {
- outputStream = new FileStream(localFileName, FileMode.Append);
- if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
- {
- throw new Exception("ftp下载目标服务器地址未设置!");
- }
- Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
- ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
- ftpsize.UseBinary = true;
- ftpsize.ContentOffset = size;
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.UseBinary = true;
- reqFTP.KeepAlive = false;
- reqFTP.ContentOffset = size;
- if (ifCredential)//使用用户身份认证
- {
- ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- }
- ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
- FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
- long totalBytes = re.ContentLength;
- re.Close();
- reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
- response = (FtpWebResponse)reqFTP.GetResponse();
- ftpStream = response.GetResponseStream();
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)totalBytes, 0);//更新进度条
- }
- long totalDownloadedByte = 0;
- int bufferSize = 2048;
- int readCount;
- byte[] buffer = new byte[bufferSize];
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- while (readCount > 0)
- {
- totalDownloadedByte = readCount + totalDownloadedByte;
- outputStream.Write(buffer, 0, readCount);
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
- }
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- }
- ftpStream.Close();
- outputStream.Close();
- response.Close();
- return true;
- }
- catch (Exception)
- {
- return false;
- throw;
- }
- finally
- {
- if (ftpStream != null)
- {
- ftpStream.Close();
- }
- if (outputStream != null)
- {
- outputStream.Close();
- }
- if (response != null)
- {
- response.Close();
- }
- }
- }
- /// <summary>
- /// 从FTP服务器下载文件,指定本地路径和本地文件名
- /// </summary>
- /// <param name="remoteFileName">远程文件名</param>
- /// <param name="localFileName">保存本地的文件名(包含路径)</param>
- /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <param name="brokenOpen">是否断点下载:true 会在localFileName 找是否存在已经下载的文件,并计算文件流大小</param>
- /// <returns>是否下载成功</returns>
- public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, bool brokenOpen, Action<int, int> updateProgress = null)
- {
- if (brokenOpen)
- {
- try
- {
- long size = 0;
- if (File.Exists(localFileName))
- {
- using (FileStream outputStream = new FileStream(localFileName, FileMode.Open))
- {
- size = outputStream.Length;
- }
- }
- return FtpBrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);
- }
- catch
- {
- throw;
- }
- }
- else
- {
- return FtpDownload(remoteFileName, localFileName, ifCredential, updateProgress);
- }
- }
- #endregion
- #region 上传文件到FTP服务器
- /// <summary>
- /// 上传文件到FTP服务器
- /// </summary>
- /// <param name="localFullPath">本地带有完整路径的文件名</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <returns>是否下载成功</returns>
- public static bool FtpUploadFile(string localFullPathName, Action<int, int> updateProgress = null)
- {
- FtpWebRequest reqFTP;
- Stream stream = null;
- FtpWebResponse response = null;
- FileStream fs = null;
- try
- {
- FileInfo finfo = new FileInfo(localFullPathName);
- if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
- {
- throw new Exception("ftp上传目标服务器地址未设置!");
- }
- Uri uri = new Uri("ftp://" + FtpServerIP + "/" + finfo.Name);
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.KeepAlive = false;
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
- reqFTP.Method = WebRequestMethods.Ftp.UploadFile;//向服务器发出下载请求命令
- reqFTP.ContentLength = finfo.Length;//为request指定上传文件的大小
- response = reqFTP.GetResponse() as FtpWebResponse;
- reqFTP.ContentLength = finfo.Length;
- int buffLength = 1024;
- byte[] buff = new byte[buffLength];
- int contentLen;
- fs = finfo.OpenRead();
- stream = reqFTP.GetRequestStream();
- contentLen = fs.Read(buff, 0, buffLength);
- int allbye = (int)finfo.Length;
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)allbye, 0);//更新进度条
- }
- int startbye = 0;
- while (contentLen != 0)
- {
- startbye = contentLen + startbye;
- stream.Write(buff, 0, contentLen);
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)allbye, (int)startbye);//更新进度条
- }
- contentLen = fs.Read(buff, 0, buffLength);
- }
- stream.Close();
- fs.Close();
- response.Close();
- return true;
- }
- catch (Exception)
- {
- return false;
- throw;
- }
- finally
- {
- if (fs != null)
- {
- fs.Close();
- }
- if (stream != null)
- {
- stream.Close();
- }
- if (response != null)
- {
- response.Close();
- }
- }
- }
- /// <summary>
- /// 上传文件到FTP服务器(断点续传)
- /// </summary>
- /// <param name="localFullPath">本地文件全路径名称:C:\Users\JianKunKing\Desktop\IronPython脚本测试工具</param>
- /// <param name="remoteFilepath">远程文件所在文件夹路径</param>
- /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
- /// <returns></returns>
- public static bool FtpUploadBroken(string localFullPath, string remoteFilepath, Action<int, int> updateProgress = null)
- {
- if (remoteFilepath == null)
- {
- remoteFilepath = "";
- }
- string newFileName = string.Empty;
- bool success = true;
- FileInfo fileInf = new FileInfo(localFullPath);
- long allbye = (long)fileInf.Length;
- if (fileInf.Name.IndexOf("#") == -1)
- {
- newFileName = RemoveSpaces(fileInf.Name);
- }
- else
- {
- newFileName = fileInf.Name.Replace("#", "#");
- newFileName = RemoveSpaces(newFileName);
- }
- long startfilesize = GetFileSize(newFileName, remoteFilepath);
- if (startfilesize >= allbye)
- {
- return false;
- }
- long startbye = startfilesize;
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)allbye, (int)startfilesize);//更新进度条
- }
- string uri;
- if (remoteFilepath.Length == 0)
- {
- uri = "ftp://" + FtpServerIP + "/" + newFileName;
- }
- else
- {
- uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + newFileName;
- }
- FtpWebRequest reqFTP;
- // 根据uri创建FtpWebRequest对象
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
- // ftp用户名和密码
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
- // 默认为true,连接不会被关闭
- // 在一个命令之后被执行
- reqFTP.KeepAlive = false;
- // 指定执行什么命令
- reqFTP.Method = WebRequestMethods.Ftp.AppendFile;
- // 指定数据传输类型
- reqFTP.UseBinary = true;
- // 上传文件时通知服务器文件的大小
- reqFTP.ContentLength = fileInf.Length;
- int buffLength = 2048;// 缓冲大小设置为2kb
- byte[] buff = new byte[buffLength];
- // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
- FileStream fs = fileInf.OpenRead();
- Stream strm = null;
- try
- {
- // 把上传的文件写入流
- strm = reqFTP.GetRequestStream();
- // 每次读文件流的2kb
- fs.Seek(startfilesize, 0);
- int contentLen = fs.Read(buff, 0, buffLength);
- // 流内容没有结束
- while (contentLen != 0)
- {
- // 把内容从file stream 写入 upload stream
- strm.Write(buff, 0, contentLen);
- contentLen = fs.Read(buff, 0, buffLength);
- startbye += contentLen;
- //更新进度
- if (updateProgress != null)
- {
- updateProgress((int)allbye, (int)startbye);//更新进度条
- }
- }
- // 关闭两个流
- strm.Close();
- fs.Close();
- }
- catch
- {
- success = false;
- throw;
- }
- finally
- {
- if (fs != null)
- {
- fs.Close();
- }
- if (strm != null)
- {
- strm.Close();
- }
- }
- return success;
- }
- /// <summary>
- /// 去除空格
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- private static string RemoveSpaces(string str)
- {
- string a = "";
- CharEnumerator CEnumerator = str.GetEnumerator();
- while (CEnumerator.MoveNext())
- {
- byte[] array = new byte[1];
- array = System.Text.Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());
- int asciicode = (short)(array[0]);
- if (asciicode != 32)
- {
- a += CEnumerator.Current.ToString();
- }
- }
- string sdate = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString()
- + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString();
- return a.Split('.')[a.Split('.').Length - 2] + "." + a.Split('.')[a.Split('.').Length - 1];
- }
- /// <summary>
- /// 获取已上传文件大小
- /// </summary>
- /// <param name="filename">文件名称</param>
- /// <param name="path">服务器文件路径</param>
- /// <returns></returns>
- public static long GetFileSize(string filename, string remoteFilepath)
- {
- long filesize = 0;
- try
- {
- FtpWebRequest reqFTP;
- FileInfo fi = new FileInfo(filename);
- string uri;
- if (remoteFilepath.Length == 0)
- {
- uri = "ftp://" + FtpServerIP + "/" + fi.Name;
- }
- else
- {
- uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + fi.Name;
- }
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.KeepAlive = false;
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
- reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- filesize = response.ContentLength;
- return filesize;
- }
- catch
- {
- return 0;
- }
- }
- //public void Connect(String path, string ftpUserID, string ftpPassword)//连接ftp
- //{
- // // 根据uri创建FtpWebRequest对象
- // reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
- // // 指定数据传输类型
- // reqFTP.UseBinary = true;
- // // ftp用户名和密码
- // reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
- //}
- #endregion
- }
- }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO; namespace JianKunKing.Common.Ftp
{
/// <summary>
/// ftp方式文件下载上传
/// </summary>
public static class FileUpDownload
{
#region 变量属性
/// <summary>
/// Ftp服务器ip
/// </summary>
public static string FtpServerIP = string.Empty;
/// <summary>
/// Ftp 指定用户名
/// </summary>
public static string FtpUserID = string.Empty;
/// <summary>
/// Ftp 指定用户密码
/// </summary>
public static string FtpPassword = string.Empty; #endregion #region 从FTP服务器下载文件,指定本地路径和本地文件名
/// <summary>
/// 从FTP服务器下载文件,指定本地路径和本地文件名
/// </summary>
/// <param name="remoteFileName">远程文件名</param>
/// <param name="localFileName">保存本地的文件名(包含路径)</param>
/// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
/// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
/// <returns>是否下载成功</returns>
public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, Action<int, int> updateProgress = null)
{
FtpWebRequest reqFTP, ftpsize;
Stream ftpStream = null;
FtpWebResponse response = null;
FileStream outputStream = null;
try
{ outputStream = new FileStream(localFileName, FileMode.Create);
if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
{
throw new Exception("ftp下载目标服务器地址未设置!");
}
Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
ftpsize.UseBinary = true; reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
if (ifCredential)//使用用户身份认证
{
ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
}
ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
long totalBytes = re.ContentLength;
re.Close(); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream(); //更新进度
if (updateProgress != null)
{
updateProgress((int)totalBytes, 0);//更新进度条
}
long totalDownloadedByte = 0;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
totalDownloadedByte = readCount + totalDownloadedByte;
outputStream.Write(buffer, 0, readCount);
//更新进度
if (updateProgress != null)
{
updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
}
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return true;
}
catch (Exception)
{
return false;
throw;
}
finally
{
if (ftpStream != null)
{
ftpStream.Close();
}
if (outputStream != null)
{
outputStream.Close();
}
if (response != null)
{
response.Close();
}
}
}
/// <summary>
/// 从FTP服务器下载文件,指定本地路径和本地文件名(支持断点下载)
/// </summary>
/// <param name="remoteFileName">远程文件名</param>
/// <param name="localFileName">保存本地的文件名(包含路径)</param>
/// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
/// <param name="size">已下载文件流大小</param>
/// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
/// <returns>是否下载成功</returns>
public static bool FtpBrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action<int, int> updateProgress = null)
{
FtpWebRequest reqFTP, ftpsize;
Stream ftpStream = null;
FtpWebResponse response = null;
FileStream outputStream = null;
try
{ outputStream = new FileStream(localFileName, FileMode.Append);
if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
{
throw new Exception("ftp下载目标服务器地址未设置!");
}
Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
ftpsize.UseBinary = true;
ftpsize.ContentOffset = size; reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.ContentOffset = size;
if (ifCredential)//使用用户身份认证
{
ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
}
ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
long totalBytes = re.ContentLength;
re.Close(); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream(); //更新进度
if (updateProgress != null)
{
updateProgress((int)totalBytes, 0);//更新进度条
}
long totalDownloadedByte = 0;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
totalDownloadedByte = readCount + totalDownloadedByte;
outputStream.Write(buffer, 0, readCount);
//更新进度
if (updateProgress != null)
{
updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
}
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return true;
}
catch (Exception)
{
return false;
throw;
}
finally
{
if (ftpStream != null)
{
ftpStream.Close();
}
if (outputStream != null)
{
outputStream.Close();
}
if (response != null)
{
response.Close();
}
}
} /// <summary>
/// 从FTP服务器下载文件,指定本地路径和本地文件名
/// </summary>
/// <param name="remoteFileName">远程文件名</param>
/// <param name="localFileName">保存本地的文件名(包含路径)</param>
/// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
/// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
/// <param name="brokenOpen">是否断点下载:true 会在localFileName 找是否存在已经下载的文件,并计算文件流大小</param>
/// <returns>是否下载成功</returns>
public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, bool brokenOpen, Action<int, int> updateProgress = null)
{
if (brokenOpen)
{
try
{
long size = 0;
if (File.Exists(localFileName))
{
using (FileStream outputStream = new FileStream(localFileName, FileMode.Open))
{
size = outputStream.Length;
}
}
return FtpBrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);
}
catch
{
throw;
}
}
else
{
return FtpDownload(remoteFileName, localFileName, ifCredential, updateProgress);
}
}
#endregion #region 上传文件到FTP服务器
/// <summary>
/// 上传文件到FTP服务器
/// </summary>
/// <param name="localFullPath">本地带有完整路径的文件名</param>
/// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
/// <returns>是否下载成功</returns>
public static bool FtpUploadFile(string localFullPathName, Action<int, int> updateProgress = null)
{
FtpWebRequest reqFTP;
Stream stream = null;
FtpWebResponse response = null;
FileStream fs = null;
try
{
FileInfo finfo = new FileInfo(localFullPathName);
if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
{
throw new Exception("ftp上传目标服务器地址未设置!");
}
Uri uri = new Uri("ftp://" + FtpServerIP + "/" + finfo.Name);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;//向服务器发出下载请求命令
reqFTP.ContentLength = finfo.Length;//为request指定上传文件的大小
response = reqFTP.GetResponse() as FtpWebResponse;
reqFTP.ContentLength = finfo.Length;
int buffLength = 1024;
byte[] buff = new byte[buffLength];
int contentLen;
fs = finfo.OpenRead();
stream = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
int allbye = (int)finfo.Length;
//更新进度
if (updateProgress != null)
{
updateProgress((int)allbye, 0);//更新进度条
}
int startbye = 0;
while (contentLen != 0)
{
startbye = contentLen + startbye;
stream.Write(buff, 0, contentLen);
//更新进度
if (updateProgress != null)
{
updateProgress((int)allbye, (int)startbye);//更新进度条
}
contentLen = fs.Read(buff, 0, buffLength);
}
stream.Close();
fs.Close();
response.Close();
return true; }
catch (Exception)
{
return false;
throw;
}
finally
{
if (fs != null)
{
fs.Close();
}
if (stream != null)
{
stream.Close();
}
if (response != null)
{
response.Close();
}
}
} /// <summary>
/// 上传文件到FTP服务器(断点续传)
/// </summary>
/// <param name="localFullPath">本地文件全路径名称:C:\Users\JianKunKing\Desktop\IronPython脚本测试工具</param>
/// <param name="remoteFilepath">远程文件所在文件夹路径</param>
/// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
/// <returns></returns>
public static bool FtpUploadBroken(string localFullPath, string remoteFilepath, Action<int, int> updateProgress = null)
{
if (remoteFilepath == null)
{
remoteFilepath = "";
}
string newFileName = string.Empty;
bool success = true;
FileInfo fileInf = new FileInfo(localFullPath);
long allbye = (long)fileInf.Length;
if (fileInf.Name.IndexOf("#") == -1)
{
newFileName = RemoveSpaces(fileInf.Name);
}
else
{
newFileName = fileInf.Name.Replace("#", "#");
newFileName = RemoveSpaces(newFileName);
}
long startfilesize = GetFileSize(newFileName, remoteFilepath);
if (startfilesize >= allbye)
{
return false;
}
long startbye = startfilesize;
//更新进度
if (updateProgress != null)
{
updateProgress((int)allbye, (int)startfilesize);//更新进度条
} string uri;
if (remoteFilepath.Length == 0)
{
uri = "ftp://" + FtpServerIP + "/" + newFileName;
}
else
{
uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + newFileName;
}
FtpWebRequest reqFTP;
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.AppendFile;
// 指定数据传输类型
reqFTP.UseBinary = true;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;// 缓冲大小设置为2kb
byte[] buff = new byte[buffLength];
// 打开一个文件流 (System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
Stream strm = null;
try
{
// 把上传的文件写入流
strm = reqFTP.GetRequestStream();
// 每次读文件流的2kb
fs.Seek(startfilesize, 0);
int contentLen = fs.Read(buff, 0, buffLength);
// 流内容没有结束
while (contentLen != 0)
{
// 把内容从file stream 写入 upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
startbye += contentLen;
//更新进度
if (updateProgress != null)
{
updateProgress((int)allbye, (int)startbye);//更新进度条
}
}
// 关闭两个流
strm.Close();
fs.Close();
}
catch
{
success = false;
throw;
}
finally
{
if (fs != null)
{
fs.Close();
}
if (strm != null)
{
strm.Close();
}
}
return success;
} /// <summary>
/// 去除空格
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static string RemoveSpaces(string str)
{
string a = "";
CharEnumerator CEnumerator = str.GetEnumerator();
while (CEnumerator.MoveNext())
{
byte[] array = new byte[1];
array = System.Text.Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());
int asciicode = (short)(array[0]);
if (asciicode != 32)
{
a += CEnumerator.Current.ToString();
}
}
string sdate = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString()
+ System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString();
return a.Split('.')[a.Split('.').Length - 2] + "." + a.Split('.')[a.Split('.').Length - 1];
}
/// <summary>
/// 获取已上传文件大小
/// </summary>
/// <param name="filename">文件名称</param>
/// <param name="path">服务器文件路径</param>
/// <returns></returns>
public static long GetFileSize(string filename, string remoteFilepath)
{
long filesize = 0;
try
{
FtpWebRequest reqFTP;
FileInfo fi = new FileInfo(filename);
string uri;
if (remoteFilepath.Length == 0)
{
uri = "ftp://" + FtpServerIP + "/" + fi.Name;
}
else
{
uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + fi.Name;
}
reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
filesize = response.ContentLength;
return filesize;
}
catch
{
return 0;
}
} //public void Connect(String path, string ftpUserID, string ftpPassword)//连接ftp
//{
// // 根据uri创建FtpWebRequest对象
// reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
// // 指定数据传输类型
// reqFTP.UseBinary = true;
// // ftp用户名和密码
// reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
//} #endregion }
}
调用实例:
下载(不需要带iis部分的路径):
- FileUpDownload.FtpServerIP = "192.168.1.1";
- FileUpDownload.FtpUserID = "ftpTest001";
- FileUpDownload.FtpPassword = "aaaaaa";
- FileUpDownload.FtpDownload("Beyond Compare(绿色免安装).zip",
- Application.StartupPath + "/downloads/crm2.ra6", false);
FileUpDownload.FtpServerIP = "192.168.1.1";
FileUpDownload.FtpUserID = "ftpTest001";
FileUpDownload.FtpPassword = "aaaaaa";
FileUpDownload.FtpDownload("Beyond Compare(绿色免安装).zip",
Application.StartupPath + "/downloads/crm2.ra6", false);
之前的上传的文件目录:
上传(不需要带iis部分的路径):
- OpenFileDialog op = new OpenFileDialog();
- op.InitialDirectory = Application.StartupPath;
- op.RestoreDirectory = true;
- op.Filter = "压缩文件(*.zip)|*.zip|压缩文件(*.rar)|*.rar|所有文件(*.*)|*.*";
- if (op.ShowDialog() == DialogResult.OK)
- {
- string aa = op.FileName;
- FileUpDownload.FtpServerIP = "192.168.1.1";
- FileUpDownload.FtpUserID = "ftpTest001";
- FileUpDownload.FtpPassword = "aaaaaa";
- //全路径
- FileUpDownload.FtpUploadFile(aa);
- }
OpenFileDialog op = new OpenFileDialog();
op.InitialDirectory = Application.StartupPath;
op.RestoreDirectory = true;
op.Filter = "压缩文件(*.zip)|*.zip|压缩文件(*.rar)|*.rar|所有文件(*.*)|*.*";
if (op.ShowDialog() == DialogResult.OK)
{
string aa = op.FileName;
FileUpDownload.FtpServerIP = "192.168.1.1";
FileUpDownload.FtpUserID = "ftpTest001";
FileUpDownload.FtpPassword = "aaaaaa";
//全路径
FileUpDownload.FtpUploadFile(aa);
}
IIS下搭建FTP服务器:点击打开链接
将文件分段,分段后,每段启用一个线程来下载(提供一个属性或者入参,来控制启用多少个线程),下载完成后,将文件拼起来(跟断点续传的原理差不多)
具体可以百度搜索:c# ftp 多线程 下载
C# FTP上传下载(支持断点续传)的更多相关文章
- 【FTP】FTP文件上传下载-支持断点续传
Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常 ...
- FTP上传下载工具(FlashFXP) v5.5.0 中文版
软件名称: FTP上传下载工具(FlashFXP) 软件语言: 简体中文 授权方式: 免费试用 运行环境: Win 32位/64位 软件大小: 7.4MB 图片预览: 软件简介: FlashFXP 是 ...
- JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)
package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...
- windows系统下ftp上传下载和一些常用命令
先假设一个ftp地址 用户名 密码 FTP Server: home4u.at.china.com User: yepanghuang Password: abc123 打开windows的开始菜单, ...
- windows下ftp上传下载和一些常用命令
先假设一个ftp地址 用户名 密码 FTP Server: home4u.at.china.com User: yepanghuang Password: abc123 打开windows的开始菜单, ...
- 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)
前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上 ...
- C# -- FTP上传下载
C# -- FTP上传下载 1. C#实现FTP下载 private static void TestFtpDownloadFile(string strFtpPath, string strFile ...
- Java.ftp上传下载
1:jar的maven的引用: 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...
- python之实现ftp上传下载代码(含错误处理)
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之实现ftp上传下载代码(含错误处理) #http://www.cnblogs.com/kait ...
- python之模块ftplib(实现ftp上传下载代码)
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块ftplib(实现ftp上传下载代码) #需求:实现ftp上传下载代码(不含错误处理) f ...
随机推荐
- HTML和CSS标签命名规则
1.Images 存放一些网站常用的图片: 2.Css 存放一些CSS文件: 3.Flash 存放一些Flash文件: 4.PSD 存放一些PSD源文件: 5.Temp 存放所有临时图片和其它文件: ...
- webpack的devtool
这里以环境分类为分析方向 1.对开发环境 eval - 每个模块都使用 eval() 执行,并且都有 //@ sourceURL.此选项会非常快地构建.主要缺点是,由于会映射到转换后的代码,而不是映射 ...
- 关于js私钥加密公钥解密的问题
博客荒废很久了,最近遇到一个问题,看网上的说明比较少,所以写下来给大家一个参考 一般来说rsa算法都是使用公钥加密,私钥解密,或者私钥签名,公钥验签.但总有特别的时候会想要用私钥加密,公钥解密,但是j ...
- 启动 AXD 配置开发板
1. 启动 AXD 先启动 DragonICE Server 程序. 按如下步聚启动 AXD: 开始>所有程序>ARM Developer Suite v1.2>AXD De ...
- 我也可以独立(引用JS外部文件)
我也可以独立(引用JS外部文件) 通过前面知识学习,我们知道使用<script>标签在HTML文件中添加JavaScript代码,如图: JavaScript代码只能写在HTML文件中吗? ...
- amaze UI(mark)
为移动而生 Amaze UI 以移动优先(Mobile first)为理念,从小屏逐步扩展到大屏,最终实现所有屏幕适配,适应移动互联潮流. 组件丰富,模块化 Amaze UI 含近 20 个 CSS ...
- range和arange
a = np.arange(12) print(a, type(a)) b = range(10) print(b, type(b)) li = list(b) print(li) 拓展: 两个参数: ...
- CSIC_716_20191115【内置函数、递归、模块、软件开发规范】
内置函数 map map映射:语法结构(函数对象,可迭代对象) 依次从可迭代对象中取值,然后给函数做运算,再依次返回运算的结果. ss = map(lambda x: x + x, [1, 2, 3] ...
- css悬浮在页面顶端
.header{ position:fixed; margin-top:; width:%; z-index:; } .body{ position:relative; padding-top:119 ...
- leetcode-240-搜索二维矩阵②
题目描述: 最佳方法:O(m+n) O(1) class Solution: def searchMatrix(self, matrix, target): if not matrix : retur ...