C# .NET,FTP帮助类,上传,下载,删除 FTP服务端文件

180it 2024-11-19 AM 80℃ 0条
public class FTPHelper
{
    private static string FTPCONSTR = "ftp://192.168.1.23:21";
    private static string FTPUSERNAME = "lqwvje";//FTP服务器的用户名
    private static string FTPPASSWORD = "123456";//FTP服务器的密码
 
 
    /// <summary>
    /// 上传文件到远程ftp
    /// </summary>
    /// <param name="ftpPath">ftp服务端的文件路径</param>
    /// <param name="path">本地的文件目录</param>
    /// <returns></returns>
    public static bool UploadFile(string ftpPath, string localPath)
    {
        FileInfo f = new FileInfo(localPath);
        if (!MakeDir(ftpPath))
        {
            return false;
        }
        string path = FTPCONSTR + ftpPath + Path.GetFileName(localPath);
        FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
        reqFtp.UseBinary = true;
        reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
        reqFtp.KeepAlive = false;
        reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
        reqFtp.ContentLength = f.Length;
        int buffLength = 2048;
        byte[] buff = new byte[buffLength];
        int contentLen;
        FileStream fs = f.OpenRead();
        try
        {
            Stream strm = reqFtp.GetRequestStream();
            contentLen = fs.Read(buff, 0, buffLength);
            while (contentLen != 0)
            {
                strm.Write(buff, 0, contentLen);
                contentLen = fs.Read(buff, 0, buffLength);
            }
            strm.Close();
            fs.Close();
            return true;
        }
        catch (Exception ex)
        {
            string ERR = ex.Message;
            return false;
        }
    }
 
 
    /// <summary>
    /// 从ftp服务器下载文件的功能
    /// </summary>
    /// <param name="ftpFilePath">ftp下载的文件地址</param>
    /// <param name="localPath">存放到本地的路径</param>
    /// <returns></returns>
    public static bool Download(string ftpFilePath, string localPath)
    {
        try
        {
            string newFileName = Path.Combine(localPath, Path.GetFileName(ftpFilePath));
            if (File.Exists(newFileName))
            {
                File.Delete(newFileName);
            }
 
            FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(FTPCONSTR + ftpFilePath));
            reqFtp.UseBinary = true;
            reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
            FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
            Stream ftpStream = response.GetResponseStream();
            //long cl = response.ContentLength;
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[bufferSize];
            readCount = ftpStream.Read(buffer, 0, bufferSize);
            FileStream outputStream = new FileStream(newFileName, FileMode.Create);
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }
            ftpStream.Close();
            outputStream.Close();
            response.Close();
            return true;
        }
        catch (Exception ex)
        {
            string err = ex.Message;
            return false;
        }
    }
 
    /// <summary>
    /// 获得文件大小
    /// </summary>
    /// <param name="url">FTP服务端文件路径</param>
    /// <returns></returns>
    public static long GetFileSize(string ftpFilePath)
    {
        long fileSize = 0;
        try
        {
            FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(FTPCONSTR + ftpFilePath));
            reqFtp.UseBinary = true;
            reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
            reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
            FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
            fileSize = response.ContentLength;
 
            response.Close();
        }
        catch (Exception ex)
        {
            string s = ex.Message;
            return -1;
        }
        return fileSize;
    }
 
    /// <summary>
    ///在ftp服务器上创建文件目录
    /// </summary>
    /// <param name="dirName">服务端文件目录</param>
    /// <returns></returns>
    public static bool MakeDir(string dirName)
    {
        try
        {
            string[] ds = dirName.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            string tempPath = "/";
            foreach (string s in ds)
            {
                tempPath += s + "/";
                if (!RemoteFtpDirExists(tempPath))
                {
                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPCONSTR + tempPath);
                    request.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
                    request.Method = WebRequestMethods.Ftp.MakeDirectory;
                    request.GetResponse();
                    request.Abort();
                }
            }
            return true;
        }
        catch (Exception ex)
        {
            string msg = ex.Message;
            return false;
        }
    }
    /// <summary>
    /// 判断ftp服务端的文件目录是否存在
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static bool RemoteFtpDirExists(string ftpPath)
    {
        FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(FTPCONSTR + ftpPath));
        reqFtp.UseBinary = true;
        reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
        reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
        FtpWebResponse resFtp = null;
        try
        {
            resFtp = (FtpWebResponse)reqFtp.GetResponse();
            //FtpStatusCode code = resFtp.StatusCode;//OpeningData
            resFtp.Close();
            return true;
        }
        catch
        {
            if (resFtp != null)
            {
                resFtp.Close();
            }
            return false;
        }
    }
 
 
    /// <summary>
    /// 从ftp服务器删除文件的功能
    /// </summary>
    /// <param name="ftpFilePath">ftp服务端文件地址</param>
    /// <returns></returns>
    public static bool DeleteFile(string ftpFilePath)
    {
        try
        {
            FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(FTPCONSTR + ftpFilePath));
            reqFtp.UseBinary = true;
            reqFtp.KeepAlive = false;
            reqFtp.Method = WebRequestMethods.Ftp.DeleteFile;
            reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
            FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
            response.Close();
            return true;
        }
        catch (Exception ex)
        {
            //errorinfo = string.Format("因{0},无法下载", ex.Message);
            return false;
        }
    }
 
    /// <summary>
    /// 获取文件和目录列表
    /// </summary>
    /// <returns></returns>
    public static string[] GetList(string ftpPath = "")
    {
        try
        {
            StringBuilder result = new StringBuilder();
            FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(FTPCONSTR + ftpPath));
            ftp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
            ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
            WebResponse response = ftp.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);//读入responses所创建的数据流
            string line = reader.ReadLine();
            while (line != null)
            {
                result.AppendLine(line);
                line = reader.ReadLine();
            }
            reader.Close();
            response.Close();
            return result.ToString().Split('\n');
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

方法调用

//上传文件到FTP服务端
FTPHelper.UploadFile("/root/2/24/6/221.txt", "C:\\221.txt");
//从FTP服务端下载文件
FTPHelper.Download("/root/2/24/6/221.txt", "C:\\");
//删除FTP服务端文件
FTPHelper.DeleteFile("/root/2/24/6/221.txt");
//获取FTP文件和目录列表
FTPHelper.GetList("/root");

本文来自 www.LuoFenMing.com

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

C# .NET,FTP帮助类,上传,下载,删除 FTP服务端文件