C#使用FtpWebRequest上传文件

System.Net命名空间下的FtpWebRequest类实现了ftp协议的.Net实现。

  • FtpWebRequest.KeepAlive指定在请求完成后服务器是否要马上关闭连接
  • FtpWebRequest.UseBinary 指定文件以二进制方式传输
  • FtpWebRequest.Method设置ftp的命令
  • WebRequestMethods.Ftp.UploadFile是上传文件的命令

使用FtpWebRequest对象上传文件时,需要向GetRequestStream方法返回的Stream中写入数据。

需要引用如下命名空间

using System.Net; using System.IO;

FTP上传文件代码实现:

public void ftpfile(string ftpfilepath, string inputfilepath) { string ftphost = "127.0.0.1"; //here correct hostname or IP of the ftp server to be given  string ftpfullpath = "ftp://" + ftphost + ftpfilepath; FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); ftp.Credentials = new NetworkCredential("userid", "password"); //userid and password for the ftp server to given  ftp.KeepAlive = true; ftp.UseBinary = true; ftp.Method = WebRequestMethods.Ftp.UploadFile; FileStream fs = File.OpenRead(inputfilepath); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); Stream ftpstream = ftp.GetRequestStream(); ftpstream.Write(buffer, 0, buffer.Length); ftpstream.Close(); }

调用方法:

ftpfile(@"/testfolder/testfile.xml", @"c:\testfile.xml");

你可能感兴趣的:(C#使用FtpWebRequest上传文件)