欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Ftp操作类

程序员文章站 2022-07-27 23:11:00
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks;... ......
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Solution.Common
{

    public class FtpHelper
    {
        private FtpHelper()
        {

        }

        private static FtpHelper _instance;

        private static readonly object obj = new object();


        //懒汉式,双重检查锁定
        public static FtpHelper GetInstance()
        {
            if (_instance == null)
            {
                lock (obj)
                {
                    if (_instance == null)
                    {
                        _instance = new FtpHelper();
                    }
                }
            }
            return _instance;
        }


        /// <summary>
        /// 将生成的内存流上传到Ftp服务器,并生成文件
        /// </summary>
        /// <param name="ms">待上传的文件内存流</param>
        /// <param name="userid">ftp账号</param>
        /// <param name="pwd">ftp密码</param>
        /// <param name="filename">待生成文件的名称</param>
        /// <param name="ftpPath">文件在ftp存放的路径</param>
        /// <param name="msg">返回的消息</param>
        /// <returns></returns>
        public bool Upload(MemoryStream ms, string userid, string pwd, string filename, string ftpPath, out string msg)
        {
            bool isSuccess = false;

            try
            {

                StreamWriter data_writer = new StreamWriter(ms);//为指定的文件流生成StreamWriter实例
                FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + filename));
                ftp.Credentials = new NetworkCredential(userid, pwd);//为指定的文件名称和密码
                ftp.KeepAlive = false;
                //指定执行命令
                ftp.Method = WebRequestMethods.Ftp.UploadFile;
                //指定数据传输类型
                ftp.UseBinary = true;
                //15秒超时
                ftp.Timeout = 15000;
                using (Stream ftp_stream = ftp.GetRequestStream())
                {
                    //指向内存流头
                    ms.Position = 0;
                    ms.CopyTo(ftp_stream);
                    data_writer.Close();
                    ms.Close();
                    ftp_stream.Close();
                }
                msg = "上传成功";
                isSuccess = true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                isSuccess = false;
            }
            return isSuccess;
        }



        /// <summary>
        /// 删除ftp服务器中的文件
        /// </summary>
        /// <param name="userId">ftp账号</param>
        /// <param name="pwd">ftp密码</param>
        /// <param name="ftpPath">ftp中文件的路径</param>
        /// <param name="fileName">文件名称</param>
        public bool Delete(string userId, string pwd, string ftpPath, string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, pwd);
                reqFTP.UsePassive = false;
                FtpWebResponse listResponse = (FtpWebResponse)reqFTP.GetResponse();
                listResponse.Close();
                return true;
                //string sStatus = listResponse.StatusDescription;
            }
            catch (Exception ex)
            {
                return false;
            }
        }




        ///下载文件
        //userId:ftp账号,pwd:ftp密码,filename:文件名(类似E:\DBCenter\text.xml),ftpPath:ftp路径,Msg:输出信息  
        public bool Download(string userId, string pwd, string ftpPath, string filePath, string fileName, out string Msg)
        {
            bool isSuccess = false;
            Msg = string.Empty;
            FtpWebRequest reqFTP;
            FtpWebRequest reqFTP1;

            try 
            {
                FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, pwd);
                reqFTP.UsePassive = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long cl = response.ContentLength;
                response.Close();
                if (cl > 0)
                {
                    reqFTP1 = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
                    reqFTP1.Method = WebRequestMethods.Ftp.DownloadFile;
                    reqFTP1.UseBinary = true;
                    reqFTP1.Credentials = new NetworkCredential(userId, pwd);
                    reqFTP1.UsePassive = true;
                    int bufferSize = 2048;
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    FtpWebResponse response1 = (FtpWebResponse)reqFTP1.GetResponse();
                    Stream ftpStream = response1.GetResponseStream();
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                        isSuccess = true;
                    }
                    ftpStream.Close();
                    outputStream.Close();
                    response1.Close();
                }


            }
            catch(Exception ex)
            {
                isSuccess = false;
                Msg = "程序出现异常:" + ex.Message;
            }
            return isSuccess;


        }
    }
}