赵小黑 发表于 2015-5-29 10:56:01

C# FTP上传类

代码



using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
namespace DataService_Client
{
    class Ftp
    {
      ///
      /// FTP上传
      ///
      /// 地址
      /// 用户名
      /// 密码
      /// 文件名      
      /// FTP路径
      /// 本机路径      
      ///
      public static bool Upload(string strAddress, string strUser, string strPassword, string strfilename, string destPath, string sourcePath)
      {
            bool flag = false;
            //获取文件对象
            FileInfo info = new FileInfo(sourcePath + strfilename);
            string uriString = "ftp://" + strAddress + "/" + info.Name;
            if (destPath != "")
            {
                uriString = "ftp://" + strAddress + "/" + destPath + "/" + info.Name;
            }
            try
            {
                // 根据uri创建FtpWebRequest对象
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uriString);
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(strUser, strPassword);
                // 销毁到服务器的连接
                reqFTP.KeepAlive = true;
                // 获取或设置要发送到 FTP 服务器的命令。
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                // 传输文件的数据格式Binary
                reqFTP.UseBinary = true;
                // 文件是多大
                reqFTP.ContentLength = info.Length;
                // 缓冲大小设置为2kb
                int buffLength = 2048;
                byte[] buff = new byte;
                int contentLen;
                Stream strm = reqFTP.GetRequestStream();
                // 把文件读入到流中
                FileStream fs = info.OpenRead();
                // 用于存储要由当前请求发送到服务器的数据。把文件流分装成小的字节数组,防止占用太多的服务器内存
                contentLen = fs.Read(buff, 0, buffLength);
                // 循环把文件流写入待发给ftp服务器的请求流中
                while (contentLen != 0)
                {
                  strm.Write(buff, 0, contentLen);
                  contentLen = fs.Read(buff, 0, buffLength);
                }
                fs.Close();
                strm.Close();
                flag = true;
            }
            catch (Exception ex)
            {
                TPCClass.TPCCommonCls.AddErrorMsg("Upload", ex.Message, "Ftp.txt");
            }
            return flag;
      }
    }
}

  
页: [1]
查看完整版本: C# FTP上传类