网站首页 博客 C#使用FTP方式上传文件
需要用到的命名空间:
using System.IO; using System.Net;
FTP上传类定义:
public class FtpHelper { /// <summary> /// 上传文件 /// </summary> /// <param name="fileinfo">需要上传的文件</param> /// <param name="targetDir">目标路径</param> /// <param name="hostname">ftp地址</param> /// <param name="username">ftp用户名</param> /// <param name="password">ftp密码</param> public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password, string filename) { if (targetDir.Trim() == "" || filename.Trim() == "") { return; } string URI = "ftp://" + hostname + "/" + targetDir + "/" + filename; CreateRemoteDir(hostname, username, password, targetDir); //检查是否有同名文件,如有则删除 bool sameexist = RemoteFileExists(hostname, username, password, targetDir + "/" + filename); if (sameexist) { d.e.l.e.t.eRemoteFile(hostname, username, password, targetDir + "/" + filename); } System.Net.FtpWebRequest ftp = GetRequest(URI, username, password); //设置FTP命令 设置所要执行的FTP命令, //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表 ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile; //指定文件传输的数据类型 ftp.UseBinary = true; ftp.UsePassive = true; //告诉ftp文件大小 ftp.ContentLength = fileinfo.Length; //缓冲大小设置为2KB const int BufferSize = 2048; byte[] content = new byte[BufferSize - 1 + 1]; int dataRead; //打开一个文件流 (System.IO.FileStream) 去读上传的文件 using (FileStream fs = fileinfo.OpenRead()) { try { //把上传的文件写入流 using (Stream rs = ftp.GetRequestStream()) { do { //每次读文件流的2KB dataRead = fs.Read(content, 0, BufferSize); rs.Write(content, 0, dataRead); } while (!(dataRead < BufferSize)); rs.Close(); } } catch (Exception ex) { //string errorinfo = ex.Message; } finally { fs.Close(); } } ftp = null; } //创建ftp连接 private static FtpWebRequest GetRequest(string URI, string username, string password) { //根据服务器信息FtpWebRequest创建类的对象 FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI); //提供身份验证信息 result.Credentials = new System.Net.NetworkCredential(username, password); //设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true result.KeepAlive = false; return result; } //在ftp服务器上创建目录 public static bool CreateRemoteDir(string hostname, string username, string password, string dirName) { try { bool b = RemoteDirExists(hostname, username, password, dirName); if (b) { return true; } string url = "ftp://" + hostname + "/" + dirName; FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url)); reqFtp.UseBinary = true; // reqFtp.KeepAlive = false; reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory; reqFtp.Credentials = new NetworkCredential(username, password); FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse(); response.Close(); return true; } catch (Exception ex) { //string errorinfo = ex.Message; return false; } } //判断ftp上的目录是否存在 public static bool RemoteDirExists(string hostname, string username, string password, string path) { path = "ftp://" + hostname + "/" +path; FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path)); reqFtp.UseBinary = true; reqFtp.Credentials = new NetworkCredential(username, password); reqFtp.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse resFtp = null; try { resFtp = (FtpWebResponse)reqFtp.GetResponse(); FtpStatusCode code = resFtp.StatusCode;//OpeningData resFtp.Close(); return true; } catch { if (resFtp != null) { resFtp.Close(); } return false; } } //判断ftp上的文件是否存在 public static bool RemoteFileExists(string hostname, string username, string password, string filepath) { bool result = true; FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + hostname + "/" + filepath); request.Credentials = new NetworkCredential(username, password); request.Method = WebRequestMethods.Ftp.GetFileSize; try { FtpWebResponse response = (FtpWebResponse)request.GetResponse(); } catch (WebException ex) { FtpWebResponse response = (FtpWebResponse)ex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { result = false; //文件不存在 } } request = null; return result; } //删除ftp上的文件 public static bool d.e.l.e.t.eRemoteFile(string hostname, string username, string password, string filepath) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + hostname + "/" + filepath); request.Credentials = new NetworkCredential(username, password); request.Method = WebRequestMethods.Ftp.d.e.l.e.t.eFile; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); bool result = response.StatusCode == FtpStatusCode.CommandOK || response.StatusCode == FtpStatusCode.FileActionOK; response.Close(); request = null; return result; } }
上传文件用法:
string ftpserver = "192.168.1.250"; //FTP服务器 int ftpport = 2121; //FTP端口号 string ftpuser = "hello"; //FTP用户名 string ftppass = "world"; //FTP密码 string year = DateTime.Now.Year.ToString(); string month = DateTime.Now.Month.ToString(); string day = DateTime.Now.Day.ToString(); string savepath = year + month + "/" + day; //FTP保存路径 string savename = "test_save.png"; //FTP保存文件名 FileInfo fileinfo = new FileInfo("D:\\test.png"); FtpHelper.UploadFile(fileinfo, savepath, ftpserver + ":" + ftpport, ftpuser, ftppass, savename);