ftp上传单一文件示例

2021-03-09 21:28

阅读:689

标签:sep   bre   bsp   stream   name   上传文件   except   pip   catch   

废话不多说,直接上代码

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 else 15 Console.WriteLine("失败"); 16 Console.ReadKey(); 17 } 18 19 20 /// 21 /// 上传文件 22 /// 23 /// 本机上要上传的文件的物理路径 24 /// ftp uri 25 /// 用户名 26 /// 密码 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 try 47 { 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 }

 

ftp上传单一文件示例

标签:sep   bre   bsp   stream   name   上传文件   except   pip   catch   

原文地址:https://www.cnblogs.com/baylor2019/p/12861250.html


评论


亲,登录后才可以留言!