FtpWebRequest 实现向FTP服务器上传文件
最近一个虚拟打印的需求 就是监听文件然后把文件上传到Ftp服务器上 自己c#实现封装了个上传类 用着还不错 这里分享下
public class FtpUpload { string _host { get; set; } string _port { get; set; } string _user { get; set; } string _password { get; set; } string _relative { get; set; } string _usepassive { get; set; } private FtpUpload(string host, string port, string user, string password,string relative,string usepassive) { _host = host; _port = port; _user = user; _password = password; _relative = relative; _usepassive = usepassive; } public static FtpUpload Create() { //ftp服务器IP string UploadServerHost = ConfigurationManager.AppSettings.Get("UploadServerHost"); //端口 string UploadServerPort = ConfigurationManager.AppSettings.Get("UploadServerPort"); //相对目录 string RelativeDirectory = ConfigurationManager.AppSettings.Get("RelativeDirectory"); //用户名 string UserName = ConfigurationManager.AppSettings.Get("UserName"); //密码 string UserPassword = ConfigurationManager.AppSettings.Get("UserPassword"); //被动模式 string UsePassive=ConfigurationManager.AppSettings.Get("UsePassive"); return new FtpUpload(UploadServerHost, UploadServerPort, UserName, UserPassword, RelativeDirectory, UsePassive); } public bool Connected() { byte[] buf = new byte[1024]; TcpClient b = new TcpClient(); int portInt = 0; int.TryParse(_port, out portInt); b.Connect(_host, portInt); //IP及端口 return b.Connected; } ////// 上传文件 /// /// /// public bool Upload(string LoctionPath) { try { if (!_relative.StartsWith("/")) { _relative = $"/{_relative}"; } _relative.Replace("//", "/"); string RelativePath = $"ftp://{_host}:{_port}/{_relative}/{Guid.NewGuid()}.pdf"; FtpWebRequest FtpClient = (FtpWebRequest)FtpWebRequest.Create(new Uri(RelativePath)); FtpClient.Credentials = new NetworkCredential(_user, _password); FtpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile; FtpClient.UseBinary = true; bool UsePassive = false; bool.TryParse(_usepassive, out UsePassive); FtpClient.UsePassive = UsePassive; FtpClient.KeepAlive = false; using (FileStream fs = new FileStream(LoctionPath,FileMode.Open,FileAccess.ReadWrite,FileShare.ReadWrite)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); fs.Dispose(); using (Stream ftpstream = FtpClient.GetRequestStream()) { ftpstream.Write(buffer, 0, buffer.Length); ftpstream.Close(); ftpstream.Dispose(); } } return true; } catch (Exception ex) { Log4Net.Error($"【Ftp文件上传失败】 {LoctionPath}", ex); } return false; } }
调用例子
FtpUpload ftp=FtpUpload.Create();
ftp.Upload("文件地址")