可以做个类:
1 #region FTP 2 3 string ftpServerIP; // FTP服务器的地址 4 string ftpRemotePath; // FTP目录 5 string ftpUserID; // FTP用户ID 6 string ftpPassword; // FTP密码 7 string ftpURI; // FTP URI 8 9 /// <summary> 10 /// 连接FTP 11 /// </summary> 12 /// <param name="FtpServerIP">FTP连接地址</param> 13 /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param> 14 /// <param name="FtpUserID">用户名</param> 15 /// <param name="FtpPassword">密码</param> 16 public void FtpInitial(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword) 17 { 18 ftpServerIP = FtpServerIP; 19 ftpRemotePath = FtpRemotePath; 20 ftpUserID = FtpUserID; 21 ftpPassword = FtpPassword; 22 ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; 23 } 24 25 /// <summary> 26 /// 连接FTP 27 /// </summary> 28 /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param> 29 public void FtpInitial(string FtpRemotePath) 30 { 31 ftpServerIP = "10.0.0.1"; 32 ftpRemotePath = FtpRemotePath; 33 ftpUserID = "ftp_user_id"; 34 ftpPassword = "pwd"; 35 ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; 36 } 37 38 /// <summary> 39 /// 使用FTP上传 40 /// </summary> 41 /// <param name="filename">上传的文件名</param> 42 public void FtpUpload(string filename) 43 { 44 FileInfo fileInf = new FileInfo(filename); 45 string uri = ftpURI + fileInf.Name; 46 FtpWebRequest reqFTP; 47 48 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));// 根据uri创建FtpWebRequest对象 49 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 50 reqFTP.KeepAlive = false; 51 reqFTP.Method = WebRequestMethods.Ftp.UploadFile; 52 reqFTP.UseBinary = true; 53 reqFTP.ContentLength = fileInf.Length; 54 int buffLength = 2048; 55 byte[] buff = new byte[buffLength]; 56 int contentLen; 57 FileStream fs = fileInf.OpenRead(); 58 try 59 { 60 Stream strm = reqFTP.GetRequestStream(); 61 contentLen = fs.Read(buff, 0, buffLength); 62 while (contentLen != 0) 63 { 64 strm.Write(buff, 0, contentLen); 65 contentLen = fs.Read(buff, 0, buffLength); 66 } 67 strm.Close(); 68 fs.Close(); 69 } 70 catch (Exception ex) 71 { 72 Console.WriteLine(ex.Message); 73 } 74 } 75 76 #endregion
时间: 2024-12-14 05:27:30