c#ftp操作全解:创建删除目录,上传下载文件,删除移动文件,文件改名,文件目录查询

全栈工程师开发手册 (作者:栾鹏)
c#教程全解

c#实现ftp的操作。包括创建删除目录,上传下载文件,删除移动文件,文件改名,文件目录查询。

在调试ftp前,需要在目标主机上开启ftp功能。这里在本机上调试,目标主机也是本机。ftp信息如下表

这里写图片描述

主机地址192.168.8.101,端口号使用默认21端口,开启了匿名登录。所以在代码中登陆ftp账号密码为空。

测试代码

static void Main()
{
    FtpWeb ftp=new FtpWeb("192.168.8.101","","","");  //匿名登陆ftp
    if (!ftp.DirectoryExist("", "lp"))   //判断指定目录下是否存在指定的子目录
    {
        System.Console.WriteLine("ftp上lp文件夹内存在lp1文件夹");
        ftp.MakeDir("lp");  //创建一个lp的文件夹
        ftp.MakeDir("lp/lp1");  //创建一个lp1的子文件夹
        
    }
    if (!ftp.DirectoryExist("lp", "lp2")) //判断指定目录是否存在一个子文件夹
    {
        ftp.MakeDir("lp/lp2");  //创建一个lp2的子文件夹
    }
    if (!ftp.FileExist("lp", "test.txt"))   //判断指定目录下是否存在指定的文件
    {
        System.Console.WriteLine("ftp上lp文件夹内存在test.txt文件");
        ftp.Upload("J:\\test.txt", "lp/test.txt");   //将本地J:\\test.txt文件上传到ftp目录下lp/test.txt
    }
    
    ftp.Download("lp/test.txt", "J:\\test1.txt");   //将ftp目录下stk/test.txt下载到本地J:\\test.txt文件
    
    string[] allfile = ftp.GetFilesDetailList("lp");  //获取ftp根目录下lp文件夹内的明细(包含文件和文件夹)
    foreach (string str in allfile)
    {
        System.Console.WriteLine(str);
    }
    allfile = ftp.GetDirectoryList("lp");   //获取指定目录下的文件夹列表
    foreach (string str in allfile)
    {
        System.Console.WriteLine(str);
    }

    long filesize = ftp.GetFileSize("lp/test.txt");  //查询指定文件的大小
    ftp.ReName("lp/test.txt", "test1.txt");  //将指定文件改名,只能相同目录
    ftp.MovieFile("lp/test1.txt", "test2.txt");  //将指定文件移动,只能相同目录
    ftp.Delete("lp/test2.txt");   //删除ftp上的文件
    ftp.RemoveDirectory("lp/lp2");   //删除ftp上的lp2文件夹(ftp要求只能删除空的目录,除非先删除里面的文件)
}

    }
}

ftp工具类的实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Net;
using System.IO;
using System.Windows.Forms;

namespace util
{
    public class FtpWeb
    {
        string ftpServerIP;
        string ftpRemotePath;
        string ftpUserID;
        string ftpPassword;
        string ftpURI;

        // 连接FTP
        //FtpRemotePath指定FTP连接成功后的当前目录, 如果不指定即默认为根目录
        public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
        {
            ftpServerIP = FtpServerIP;
            ftpRemotePath = FtpRemotePath;
            ftpUserID = FtpUserID;
            ftpPassword = FtpPassword;
            ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
        }

        // 上传
        public void Upload(string localpath,string urlpath)
        {
            FileInfo fileInf = new FileInfo(localpath);
            string uri = ftpURI + urlpath;
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.KeepAlive = false;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = fileInf.Length;
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            FileStream fs = fileInf.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();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        // 下载
        public void Download(string urlpath,string localpath)
        {
            FtpWebRequest reqFTP;
            try
            {
                FileStream outputStream = new FileStream(localpath, FileMode.Create);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + urlpath));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, 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);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        // 删除文件
        public void Delete(string urlpath)
        {
            try
            {
                string uri = ftpURI + urlpath;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        // 删除文件夹
        public void RemoveDirectory(string urlpath)
        {
            try
            {
                string uri = ftpURI + urlpath;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        //获取指定目录下明细(包含文件和文件夹)
        public string[] GetFilesDetailList(string urlpath)
        {
            string[] downloadFiles;
            try
            {
                bool getin=false;
                string uri = ftpURI + urlpath;
                StringBuilder result = new StringBuilder();
                FtpWebRequest ftp;
                ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string line = reader.ReadLine();
                while (line != null)
                {
                    getin = true;
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                if(getin)
                    result.Remove(result.ToString().LastIndexOf("\n"), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                downloadFiles = null;
                MessageBox.Show(ex.ToString());
                return downloadFiles;
            }
        }

        // 获取指定目录下文件列表(仅文件)
        public string[] GetFileList(string urlpath,string mask)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                string uri = ftpURI + urlpath;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string line = reader.ReadLine();
                while (line != null)
                {
                    if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
                    {
                        string mask_ = mask.Substring(0, mask.IndexOf("*"));
                        if (line.Substring(0, mask_.Length) == mask_)
                        {
                            result.Append(line);
                            result.Append("\n");
                        }
                    }
                    else
                    {
                        result.Append(line);
                        result.Append("\n");
                    }
                    line = reader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf('\n'), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                downloadFiles = null;
                if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。")
                {
                    MessageBox.Show(ex.ToString());
                }
                return downloadFiles;
            }
        }


        // 获取指定目录下所有的文件夹列表(仅文件夹)
        public string[] GetDirectoryList(string urlpath)
        {
            string[] drectory = GetFilesDetailList(urlpath);
            string m = string.Empty;
            foreach (string str in drectory)
            {
                if (str == "")
                    continue;
                int dirPos = str.IndexOf("<DIR>");
                if (dirPos > 0)
                {
                    /*判断 Windows 风格*/
                    m += str.Substring(dirPos + 5).Trim() + "\n";
                }
                else if (str.Trim().Substring(0, 1).ToUpper() == "D")
                {
                    /*判断 Unix 风格*/
                    string dir = str.Substring(54).Trim();
                    if (dir != "." && dir != "..")
                    {
                       m += dir + "\n";
                    }
                }
            }
            if (m[m.Length - 1] == '\n')
                m.Remove(m.Length - 1);
            char[] n = new char[] { '\n' };
            return m.Split(n);   //这样最后一个始终是空格了
        }

        /// 判断指定目录下是否存在指定的子目录
        // RemoteDirectoryName指定的目录名
        public bool DirectoryExist(string urlpath,string RemoteDirectoryName)
        {
            string[] dirList = GetDirectoryList(urlpath);
            foreach (string str in dirList)
            {
                if (str.Trim() == RemoteDirectoryName.Trim())
                {
                    return true;
                }
            }
           return false;
        }


        // 判断指定目录下是否存在指定的文件
        //远程文件名
        public bool FileExist(string urlpath,string RemoteFileName)
        {
            string[] fileList = GetFileList(urlpath,"*.*");
            foreach (string str in fileList)
            {
                if (str.Trim() == RemoteFileName.Trim())
                {
                    return true;
                }
            }
            return false;
        }

        // 创建文件夹
        public void MakeDir(string urlpath)
        {
            FtpWebRequest reqFTP;
            try
            {
                // dirName = name of the directory to create.
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI +urlpath));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        // 获取指定文件大小
        public long GetFileSize(string urlpath)
        {
            FtpWebRequest reqFTP;
            long fileSize = 0;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + urlpath));
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return fileSize;
        }

        // 改名
        public void ReName(string urlpath, string newname)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + urlpath));  //源路径
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = newname; //新名称
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        // 移动文件
        public void MovieFile(string urlpath, string newname)
        {
            ReName(urlpath, newname);
        }

        // 切换当前目录
        /// <param name="IsRoot">true 绝对路径   false 相对路径</param>
        public void GotoDirectory(string DirectoryName, bool IsRoot)
        {
            if (IsRoot)
            {
                ftpRemotePath = DirectoryName;
            }
            else
            {
                ftpRemotePath += DirectoryName + "/";
            }
            ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
        }

      
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

腾讯AI架构师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值