ftp上传单一文件示例

Posted baylor2019

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ftp上传单一文件示例相关的知识,希望对你有一定的参考价值。

废话不多说,直接上代码

1
class Program 2 { 3 static void Main(string[] args) 4 { 5 6 string username = "abc"; 7 string pwd = "123"; 8 string filePath = @"C:UserskevinDesktop1.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 /// <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 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上传单一文件示例的主要内容,如果未能解决你的问题,请参考以下文章

java Ftp上传创建多层文件的代码片段

ruby 使用Ruby Net :: FTP库的示例代码。登录FTP服务器,列出文件,检查目录是否存在,上传文件

php FTP文件上传示例

PHP FTP文件上传示例

ftp上传小示例

01 ftp上传简单示例客户端