using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace CallCenter.Utility { public class uploadFile { public string ftpPath; public string ftpUserID; public string ftpPassword; /// /// 上传文件 /// /// 需要上传的文件 public string UploadLocalToFtp(string localFile) { string res = ""; if (!File.Exists(localFile)) { res = "文件:“" + localFile + "” 不存在!"; return res; } FileInfo fileInf = new FileInfo(localFile); string ftpURI = "ftp://" + ftpPath + "/"; string uri = ftpURI + fileInf.Name; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));// 根据uri创建FtpWebRequest对象 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);// ftp用户名和密码 reqFTP.KeepAlive = false;// 默认为true,连接不会被关闭 // 在一个命令之后被执行 reqFTP.Method = WebRequestMethods.Ftp.UploadFile;// 指定执行什么命令 reqFTP.UseBinary = true;// 指定数据传输类型 reqFTP.ContentLength = fileInf.Length;// 上传文件时通知服务器文件的大小 int buffLength = 2048;// 缓冲大小设置为2kb byte[] buff = new byte[buffLength]; int contentLen; // 打开一个文件流 (System.IO.FileStream) 去读上传的文件 FileStream fs = fileInf.OpenRead(); try { Stream strm = reqFTP.GetRequestStream();// 把上传的文件写入流 contentLen = fs.Read(buff, 0, buffLength);// 每次读文件流的2kb while (contentLen != 0)// 流内容没有结束 { // 把内容从file stream 写入 upload stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // 关闭两个流 strm.Close(); fs.Close(); res = "上传成功!"; } catch (Exception ex) { res = "上传文件【" + ftpPath + "/" + fileInf.Name + "】时,发生错误:" + ex.Message + "
"; } return res; } /// /// 判断ftp服务器上该目录是否存在 /// /// FTP路径目录 /// 目录上的文件夹名称 /// private bool CheckDirectoryExist(string ftpPath, string dirName) { bool flag = true; try { //实例化FTP连接 FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpPath + dirName); ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword); ftp.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); } catch (Exception) { flag = false; } return flag; } /// /// 创建文件夹 /// /// FTP路径 /// 创建文件夹名称 public void MakeDir(string ftpPath, string dirName) { FtpWebRequest reqFTP; try { string ui = (ftpPath + dirName).Trim(); reqFTP = (FtpWebRequest)FtpWebRequest.Create(ui); reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); //Response.Write("文件夹【" + dirName + "】创建成功!
"); } catch (Exception ex) { //Response.Write("新建文件夹【" + dirName + "】时,发生错误:" + ex.Message); } } } }