Ftp操作类

Posted -xyl

tags:

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

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	ext.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;


        }
    }
}

 

以上是关于Ftp操作类的主要内容,如果未能解决你的问题,请参考以下文章

ftp操作类

C#工具类-FTP操作封装类FTPHelper

推荐一个java操作ftp的工具类

Ftp操作类

在“设置”片段中夸大类PreferenceScreen的错误

170404java版ftp操作工具类