首页 > 编程语言 >FTP服务器搭建及C#实现FTP文件操作

FTP服务器搭建及C#实现FTP文件操作

时间:2024-07-29 13:57:11浏览次数:7  
标签:FTP return string FtpWebRequest C# 服务器 new reqFTP response

FTP服务器搭建及C#实现FTP文件操作

1、搭建FTP服务器(以win10为例)

FTP服务器搭建及C#实现FTP文件操作_c# ftp-CSDN博客

2、代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Hk.SaaCore.Model
{
    public class FtpHelper
    {
        string ftpServerIP;
        string ftpRemotePath;
        string ftpUserID;
        string ftpPassword;
        string ftpURI;

        /// <summary>
        /// 连接FTP
        /// </summary>
        /// <param name="FtpServerIP">FTP连接地址</param>
        /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
        /// <param name="FtpUserID">用户名</param>
        /// <param name="FtpPassword">密码</param>
        public FtpHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
        {
            ftpServerIP = FtpServerIP;
            ftpRemotePath = FtpRemotePath;
            ftpUserID = FtpUserID;
            ftpPassword = FtpPassword;
            ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
        }


        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="filePath">下载保存的文件夹路径</param>
        /// <param name="fileName">文件名称</param>
        public bool Download(string filePath, string fileName)
        {
            try
            {
                FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                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();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 下载的异步方法
        /// </summary>
        /// <param name="filePath">下载保存的文件夹路径</param>
        /// <param name="fileName">文件名称</param>
        /// <returns></returns>
        public Task<bool> DownloadAsync(string filePath, string fileName)
        {
            return Task.Run(() => { return Download(filePath, fileName); });
        }

        /// <summary>
        /// 获取文件名称
        /// </summary>
        /// <param name="url">为空则获取根目录下所有</param>
        /// <returns></returns>
        public string[] GetAllList(string url)
        {
            List<string> list = new List<string>();
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(ftpURI));
            req.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            req.Method = WebRequestMethods.Ftp.ListDirectory;
            req.UseBinary = true;
            req.UsePassive = true;
            try
            {
                using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(res.GetResponseStream()))
                    {
                        string s;
                        while ((s = sr.ReadLine()) != null)
                        {
                            list.Add(s);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            return list.ToArray();
        }



        /// <summary>  
        /// 获取当前目录下明细(包含文件和文件夹)  
        /// </summary>  
        public string[] GetFilesDetailList()
        {
            try
            {
                StringBuilder result = new StringBuilder();
                FtpWebRequest ftp;
                ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
                ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                line = reader.ReadLine();
                line = reader.ReadLine();
                while (line != null)
                {
                    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)
            {
                throw new Exception(ex.Message);
            }
        }


        /// <summary>  
        /// 移动文件  
        /// </summary>  
        public void MovieFile(string currentFilename, string newDirectory)
        {
            ReName(currentFilename, newDirectory);
        }
        /// <summary>  
        /// 更改文件名  
        /// </summary> 
        public bool ReName(string currentFilename, string newFilename)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = newFilename;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>  
        /// 获取指定文件大小  
        /// </summary>  
        public long GetFileSize(string filename)
        {
            FtpWebRequest reqFTP;
            long fileSize = 0;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
                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)
            {

            }
            return fileSize;
        }
        /// <summary>  
        /// 创建文件夹  
        /// </summary>   
        public bool MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
                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();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>  
        /// 删除文件  
        /// </summary>  
        public bool Delete(string fileName)
        {
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                reqFTP.KeepAlive = false;
                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();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>  
        /// 上传  
        /// </summary>   
        public bool Upload(string filename)
        {
            FileInfo fileInf = new FileInfo(filename);
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.Name));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.KeepAlive = false;
            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();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 上传的异步方法
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public Task<bool> UploadAsync(string filename)
        {
            return Task.Run(() => { return Upload(filename); });
        }
    }
}

标签:FTP,return,string,FtpWebRequest,C#,服务器,new,reqFTP,response
From: https://www.cnblogs.com/CloakBlowing/p/18329914

相关文章

  • CTF竞赛介绍以及刷题网址(非常详细)零基础入门到精通,收藏这一篇就够了
    前言CTF(CaptureTheFlag)中文一般译作夺旗赛,在网络安全领域中指的是网络安全技术人员之间进行技术竞技的一种比赛形式。CTF起源于1996年DEFCON全球黑客大会,以代替之前黑客们通过互相发起真实攻击进行技术比拼的方式。发展至今,已经成为全球范围网络安全圈流行的竞赛形式,201......
  • LeetCode682
    classSolution{  publicintcalPoints(String[]operations){    int[]a=newint[1000];    intj=0;    intsum=0;    for(inti=0;i<operations.length;i++){        if("+".equals(operations[i])){ ......
  • 如何获取文件缩略图(C#和C++实现)
    在C++中,可以有以下两种办法使用COM接口IThumbnailCache文档链接:IThumbnailCache(thumbcache.h)-Win32apps|MicrosoftLearn示例代码如下:VOIDGetFileThumbnail(PCWSTRpath){HRESULThr=CoInitialize(nullptr);IShellItem*item=nullptr;hr=......
  • 【基础篇】Docker 架构与组件 TWO
    嗨,小伙伴们!我是小竹笋,一名热爱创作的工程师。上一篇我们聊了聊Docker的历史与发展、与虚拟机的对比以及它在行业中的应用。今天,让我们更进一步,深入探讨Docker的架构与关键组件。欢迎订阅公众号:JAVA和人工智能......
  • hackme-1靶机
    目录扫描发现该网址存放上传文件注册一个账户,点击搜索验证是否存在sql注入漏洞WindowsOS'and1=1#WindowsOS'and1=2#存在sql注入漏洞 判断列数WindowsOS'orderby3#WindowsOS'orderby4#所以,有3列;判断回显位置-1'unionselect1,2,3#查看当......
  • C语言中的函数(保姆级详细讲解)
    文章目录一.函数的概念1.1库函数1.2自定义函数二.函数的参数1.实参2.形参3.形参和实参的关系(传值调用)4.数组做函数参数(传址调用)三.函数的return语句四.函数的嵌套调用和链式访问1.嵌套调用2.链式访问五.static和extern1.作用域和生命周期2.static2.1s......
  • rsync
    rsync服务简介服务端:192.168.1.10客户端:192.168.1.20任务:将192.168.1.20的/mnt/rhd/bak/目录拷贝到192.168.1.10的/mnt/rhd1/目录下服务端安装yum-yinstallrsync配置cat/etc/rsyncd.conf|egrep-v"^#|^$"uid=rootgid=rootusechroot=nomaxconnect......
  • windows编译ZLMediaKit流媒体服务webrtc
    环境说明ZLMediaKit编译需要的软件visualstudio 2022cmake 3.29.0-rc2OpenSSL 1.1.1w(不想踩坑的话安装这个版本)libsrtp 2.6.0ZLMediaKit编译后运行需要libsrtp 编译后且配置环境变量ZLMediaKit 编译后文件cmakevisualstuido20222,自带cmakecmake可以到这两个地方......
  • 使用 pgvector 和 Lambda 生成基岩嵌入并存储在 Aurora 中
    我在Aurora中的不同表中有一些数据,我想对其执行RAG。为此,我创建了一个微服务(Lambda),它可以生成不同表的嵌入并将该数据存储在Aurora中。但是矢量更新插入应该基于某些数据库流集合。例如:如果有5个以上的数据库更新,那么我应该重新生成嵌入,并且应该有一个端点,我可以在其中......
  • 免费版ChatGPT API Key生成指南
    当下,虽然ChatGPT已经免费开放使用,但要想在互联网上畅通无阻,仍有一些繁琐步骤。虽然网络上有许多提供GPT服务的网站,但若想自行开发应用,则需要获取一个API密钥。你可以在这个项目地址查看详细信息:https://github.com/baicaigpt/FreeGPT_FreeApiKey。在该地址,你可以直接了解如何申请......