C#操作FTP总结

 本文是对FTP相关操作,例如新建/删除目录、新建/删除文件、获取文件/目录列表等的总结,方便日后调用。

  其实C#操作FTP和操作本地文件/目录差不多,尤其是对动作而言,因为它们都是文件或目录,区别在于FTP可以是远程的文件或目录等,所以需要建立一个连接,当然由于是对FTP的请求,所以会要求从本地发起一个FtpWebRequest,当然这个请求中包含一些设置,例如:请求连接的信用凭证、数据的传输格式、以及请求的FTP动作等等,FTP服务器接收到这个请求后就会返回一个FtpWebResponse了。本来微软已经提供了操作FTP的一些方法,都在System.Net命名空间下,但是感觉用起来还是不是很方便,所以自己又总结了一下,权且当作是对一个简单地封装吧,方便以后再使用的时候可以拿来就用。

  由于这些方法都比较简单,而且每个方法我都加了中文注释,所以在此就不再赘述和分别描述了,直接上代码。

using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;using System.Net;using System.IO;using System;using System.Text;using System.Configuration;using System.Linq;public class FTP_test : MonoBehaviour{ private static string url = "ftp://192.168.1.25/"; private static string userName = "mao"; private static string passWord = "mao"; // private static string pathName = ""; // Listlist; // string[] dir; void Start() { // DeleteFileOnServer(url, "2.txt"); // list = GetDirctory(url, "txt"); // Debug.Log("txt文件夹中的文件个数====" + list.Count); // dir = GetFileList(); // Debug.Log("Ftp服务器中文件总数====" + dir.Length); // int count = GetFileSize("android.txt"); // Debug.Log(count); // FileUpLoad("C:\\Users\\User\\Desktop\\doc\\民机AR检查记录软件详细设计V1.0.doc", "txt"); // MakeDir("tex/tesss"); DelDir("txt/tex"); } /// /// 删除文件

    /// ///ftp的ip地址    ///删除文件的名字    public static void DeleteFileOnServer(string serverUri, string pathName)    {        try        {            string urlPath = serverUri + pathName;            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(urlPath);            //指定数据传输类型            request.UseBinary = true;            //用户名密码            request.Credentials = new NetworkCredential(userName, passWord);            // 默认为true,连接不会被关闭            // 在一个命令之后被执行            request.KeepAlive = false;            //指定执行什么命令            request.Method = WebRequestMethods.Ftp.DeleteFile;            FtpWebResponse response = (FtpWebResponse)request.GetResponse();            response.Close();        }        catch (Exception ex)        {            Debug.Log("删除文件出错" + ex.Message);        }    }    ///    /// 从ftp服务器上获得文件夹列表

    /// ///服务器下的相对路径    ///public static ListGetDirctory(string url, string RequedstPath)    {        Liststrs = new List();        try        {            string uri = url + RequedstPath;  //目标路径 path为服务器地址            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));            // ftp用户名和密码            reqFTP.Credentials = new NetworkCredential(userName, passWord);            reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;            WebResponse response = reqFTP.GetResponse();            StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名            string line = reader.ReadLine();            while (line != null)            {                if (line.Contains(""))                {                    string msg = line.Substring(line.LastIndexOf("") + 5).Trim();                    strs.Add(msg);                }                line = reader.ReadLine();            }            reader.Close();            response.Close();            return strs;        }        catch (Exception ex)        {            Console.WriteLine("获取目录出错:" + ex.Message);        }        return strs;    }    ///    /// 获取ftp服务器上的文件和文件夹列表

    /// ///public static string[] GetFileList()    {        string[] downloadFiles;        StringBuilder result = new StringBuilder();        FtpWebRequest request;        try        {            request = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));            request.UseBinary = true;            request.Credentials = new NetworkCredential(userName, passWord);//设置用户名和密码            request.Method = WebRequestMethods.Ftp.ListDirectory;            request.UseBinary = true;            WebResponse response = request.GetResponse();            StreamReader reader = new StreamReader(response.GetResponseStream());            string line = reader.ReadLine();            Debug.Log("============开始读取内容==+ line==========");            while (line != null)            {                result.Append(line);                result.Append("\n");                line = reader.ReadLine();            }            // 删除拖尾“\n”            result.Remove(result.ToString().LastIndexOf('\n'), 1);            reader.Close();            response.Close();            return result.ToString().Split('\n');        }        catch (Exception ex)        {            Debug.Log("获取ftp上面的文件和文件夹:" + ex.Message);            downloadFiles = null;            return downloadFiles;        }    }    ///    /// 获取文件大小

    /// ///ip服务器下的相对路径    ///文件大小public static int GetFileSize(string file)    {      //  StringBuilder result = new StringBuilder();        FtpWebRequest request;        try        {            request = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + file));            Debug.Log(url + file);            request.UseBinary = true;            request.Credentials = new NetworkCredential(userName, passWord);//设置用户名和密码            request.Method = WebRequestMethods.Ftp.GetFileSize;            int dataLength = (int)request.GetResponse().ContentLength;            return dataLength;        }        catch (Exception ex)        {            Debug.Log("获取文件大小出错:" + ex.Message);            return -1;        }    }    ///    /// 文件上传

    /// ///原路径(绝对路径)包括文件名    ///目标文件夹:服务器下的相对路径 不填为根目录    public static void FileUpLoad(string filePath, string objPath = "")    {        try        {            if (objPath != "")                url += objPath + "/";            try            {                FtpWebRequest reqFTP = null;                //待上传的文件 (全路径)                try                {                    FileInfo fileInfo = new FileInfo(filePath);                    using (FileStream fs = fileInfo.OpenRead())                    {                        long length = fs.Length;                        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + fileInfo.Name));                        //设置连接到FTP的帐号密码                        reqFTP.Credentials = new NetworkCredential(userName, passWord);                        //设置请求完成后是否保持连接                        reqFTP.KeepAlive = false;                        //指定执行命令                        reqFTP.Method = WebRequestMethods.Ftp.UploadFile;                        //指定数据传输类型                        reqFTP.UseBinary = true;                        using (Stream stream = reqFTP.GetRequestStream())                        {                            //设置缓冲大小                            int BufferLength = 5120;                            byte[] b = new byte[BufferLength];                            int i;                            while ((i = fs.Read(b, 0, BufferLength)) > 0)                            {                                stream.Write(b, 0, i);                            }                            Debug.Log("上传文件成功");                        }                    }                }                catch (Exception ex)                {                    Debug.Log("上传文件失败错误为" + ex.Message);                }                finally                {                }            }            catch (Exception ex)            {                Debug.Log("上传文件失败错误为" + ex.Message);            }            finally            {            }        }        catch (Exception ex)        {            Debug.Log("上传文件失败错误为" + ex.Message);        }    }    ///    /// 新建目录 上一级必须先存在

    /// ///服务器下的相对路径    public static void MakeDir(string dirName)    {        try        {            string uri = url + dirName;            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));            // 指定数据传输类型            reqFTP.UseBinary = true;            // ftp用户名和密码            reqFTP.Credentials = new NetworkCredential(userName, passWord);            reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();            response.Close();        }        catch (Exception ex)        {            Console.WriteLine("创建目录出错:" + ex.Message);        }    }    ///    /// 删除目录 上一级必须先存在

    /// ///服务器下的相对路径    public static void DelDir(string dirName)    {        try        {            string uri = url + dirName;            Debug.Log(uri);            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));            // ftp用户名和密码            reqFTP.Credentials = new NetworkCredential(userName, passWord);            reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();            Debug.Log(response);            response.Close();        }        catch (Exception ex)        {            Console.WriteLine("删除目录出错:" + ex.Message);        }    }    ///    /// 从ftp服务器上获得文件列表

    /// ///服务器下的相对路径    ///public static ListGetFile(string RequedstPath)    {        Liststrs = new List();        try        {            string uri = url + RequedstPath;  //目标路径 path为服务器地址            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));            // ftp用户名和密码            reqFTP.Credentials = new NetworkCredential(userName, passWord);            reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;            WebResponse response = reqFTP.GetResponse();            StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名            string line = reader.ReadLine();            while (line != null)            {                if (!line.Contains(""))

                {

                    string msg = line.Substring(39).Trim();

                    strs.Add(msg);

                }

                line = reader.ReadLine();

            }

            reader.Close();

            response.Close();

            return strs;

        }

        catch (Exception ex)

        {

            Debug.Log("获取文件出错:" + ex.Message);

        }

        return strs;

    }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,798评论 19 139
  • 1、连接FTP服务器 /// /// 连接FTP服务器 /// /// FTP连接地址 /// 指定FTP连接成功...
    Solchen阅读 2,744评论 0 0
  • 读朴槿惠这本书,有三个原因,其一,在高中时刘寒梅老师在讲人物隐忍例子的时候,提到过这位韩国史上第一位女总统,这或许...
    泡泡儿seven阅读 4,042评论 2 4
  • 在最近,内心一直在纠结。我为什么而存在?人生目标是什么?我很困惑。因为我不知道自己的人生到底需要什么,如...
    鹿鹿无畏阅读 3,940评论 0 51
  • 每天我们都在等。 等一会儿在做,等一会儿在说,等一会儿在吃。等一会儿之后,很可能这件事就会被搁浅。 我一直想不明白...
    你你你你你你呀阅读 1,514评论 0 0