废话不多说,直接上代码
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 6 string username = "abc"; 7 string pwd = "123"; 8 string filePath = @"C:\Users\kevin\Desktop\1.jpg"; 9 string ftpIP = "ftp://192.168.100.104/";10 11 bool result= UploadFile(filePath, ftpIP, username, pwd);12 if (result)13 Console.WriteLine("成功");14 else15 Console.WriteLine("失败");16 Console.ReadKey();17 }18 19 20 /// <summary>21 /// 上传文件22 /// </summary>23 /// <param name="localFile">本机上要上传的文件的物理路径</param>24 /// <param name="uri">ftp uri</param>25 /// <param name="ftpUserID">用户名</param>26 /// <param name="ftpUserPwd">密码</param>27 public static bool UploadFile(string localFile, string ftpPath, string username, string password)28 {29 FileInfo fileInf = new FileInfo(localFile);30 //和原文件名字相同,也可根据需要来改传上来的文件名31 string uri = ftpPath + fileInf.Name; //tpPath + new Guid()+".jpg";改上传来的文件名32 33 FtpWebRequest reqFTP;34 35 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));36 reqFTP.Credentials = new NetworkCredential(username, password);37 reqFTP.KeepAlive = false;38 reqFTP.Method = WebRequestMethods.Ftp.UploadFile;39 reqFTP.UseBinary = true;40 reqFTP.UsePassive = false;41 reqFTP.ContentLength = fileInf.Length;42 int buffLength = 2048;43 byte[] buff = new byte[buffLength];44 int contentLen;45 FileStream fs = fileInf.OpenRead();46 try47 {48 Stream strm = reqFTP.GetRequestStream();49 contentLen = fs.Read(buff, 0, buffLength);50 while (contentLen != 0)51 {52 strm.Write(buff, 0, contentLen);53 contentLen = fs.Read(buff, 0, buffLength);54 }55 strm.Close();56 fs.Close();57 return true;58 }59 catch (Exception ex)60 {61 Console.WriteLine("Ftphelper Upload Error --> " + ex.Message);62 return false;63 }64 65 }