C#-FTP类,解决无法安装 Microsoft.AspNetCore.Http 2.2.2

VS2017 使用 Microsoft.AspNetCore.Http; 却找不到Microsoft.AspNetCore.Http命名空间,只能用NuGet安装,安装需要选用 .NETFramework,Version=v4.6.1 ,否则会出错。

因为用到 IFormFile ,需要引入两个 dll即可。
Microsoft.AspNetCore.Http
Microsoft.AspNetCore.Http.Features

在这里插入图片描述
修改后的FTP功能脚本如下

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Microsoft.AspNetCore.Http;

namespace MyFtpTools
{
    public class FtpHelper
    {
        #region FTP服务器身份验证信息      
        //private static string ftpServer = GlobalSwitch.ServerAddress;
        //private static string username = GlobalSwitch.LoginName;
        //private static string password = GlobalSwitch.LoginPWD;

        private static string ftpServer;
        private static string username;
        private static string password;

        public static string FtpServer { get => ftpServer; set => ftpServer = value; }
        public static string Username { get => username; set => username = value; }
        public static string Password { get => password; set => password = value; }        


        #endregion

        #region 上传文件

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="dir"></param>
        public static void FileUpLoad(IFormFile file, string dir)
        {
            try
            {
                //string url = Path.Combine(ftpServer, dir);
                string url = String.Format("ftp://{0}{1}", ftpServer, dir);
                string fileName = file.FileName;
                Uri uri = new Uri(Path.Combine(url, fileName));
                using (Stream fs = file.OpenReadStream())
                {
                    long length = fs.Length;
                    FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
                    reqFTP.Credentials = new NetworkCredential(username, password);
                    reqFTP.KeepAlive = false;
                    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                    reqFTP.UseBinary = true;

                    using (Stream stream = reqFTP.GetRequestStream())
                    {
                        int BufferLength = (Int32)length;
                        byte[] b = new byte[BufferLength];
                        int i;
                        while ((i = fs.Read(b, 0, BufferLength)) > 0)
                        {
                            stream.Write(b, 0, i);
                        }
                        Console.WriteLine("上传文件成功");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="filePath">原路径(绝对路径)包括文件名</param>
        /// <param name="uploadPath">目标文件夹</param>
        public static void FileUpLoad(string filePath, string uploadPath)
        {
            try
            {
                //string url = Path.Combine(ftpServer, uploadPath);  
                string url = String.Format("ftp://{0}{1}", ftpServer, uploadPath);
                try
                {
                    try
                    {
                        FileInfo fileInfo = new FileInfo(filePath);
                        using (FileStream fs = fileInfo.OpenRead())
                        {
                            long length = fs.Length;
                            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + fileInfo.Name));
                            reqFTP.Credentials = new NetworkCredential(username, password);
                            reqFTP.KeepAlive = false;
                            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                            reqFTP.UseBinary = true;
                            using (Stream stream = reqFTP.GetRequestStream())
                            {
                                int BufferLength = (Int32)length;
                                byte[] b = new byte[BufferLength];
                                int i;
                                while ((i = fs.Read(b, 0, BufferLength)) > 0)
                                {
                                    stream.Write(b, 0, i);
                                }
                                Console.WriteLine("上传文件成功");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("上传文件失败错误为" + ex.Message);
                    }
                    finally
                    {

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("上传文件失败错误为" + ex.Message);
                }
                finally
                {

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("上传文件失败错误为" + ex.Message);
            }
        }

        #endregion

        #region 下载文件

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="fileName"></param>
        /// <param name="localFile"></param>
        public static void GetFile(string dir, string fileName, string localFile)
        {
            string filedownloadPath = Path.Combine(ftpServer, dir);
            Uri uri = new Uri(Path.Combine(filedownloadPath, fileName));
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
                request.Credentials = new NetworkCredential(username, password);
                request.UseBinary = true;
                request.UsePassive = true;
                request.KeepAlive = false;
                request.Method = WebRequestMethods.Ftp.DownloadFile;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    int bufferSize = 65536;
                    using (FileStream localFileStream = new FileStream(localFile, FileMode.OpenOrCreate))
                    {
                        byte[] byteBuffer = new byte[bufferSize];
                        int bytesRead = stream.Read(byteBuffer, 0, bufferSize);

                        try
                        {
                            while (bytesRead > 0)
                            {
                                localFileStream.Write(byteBuffer, 0, bytesRead);
                                bytesRead = stream.Read(byteBuffer, 0, bufferSize);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
                response.Close();
                request = null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取文件 byte[]
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static byte[] GetFileBytes(string dir, string fileName)
        {
            int bufferSize = 65536;
            byte[] byteBuffer = new byte[bufferSize];
            string filedownloadPath = Path.Combine(ftpServer, dir);
            Uri uri = new Uri(Path.Combine(filedownloadPath, fileName));
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
                request.Credentials = new NetworkCredential(username, password);
                request.UseBinary = true;
                request.UsePassive = true;
                request.KeepAlive = false;
                request.Method = WebRequestMethods.Ftp.DownloadFile;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    stream.Read(byteBuffer, 0, bufferSize);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return byteBuffer;
        }

        #endregion

        #region 删除文件

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileName">服务器下的相对路径 包括文件名</param>
        public static void DeleteFileName(string fileName)
        {
            try
            {
                string ftpIP = ftpServer.Substring(6);
                FileInfo fileInf = new FileInfo(Path.Combine(ftpIP, fileName));
                string uri = Path.Combine(ftpServer, fileName);
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("删除文件出错:" + ex.Message);
            }
        }

        #endregion

        #region 获取文件列表

        /// <summary>
        /// 从ftp服务器上获得文件列表
        /// </summary>
        /// <param name="RequedstPath">服务器下的相对路径</param>
        /// <returns></returns>
        public static List<string> GetFile(string RequedstPath)
        {
            List<string> strs = new List<string>();
            try
            {
                string uri = Path.Combine(ftpServer, RequedstPath);
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.KeepAlive = false;
                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("<DIR>"))
                    {
                        string msg = line.Substring(39).Trim();
                        strs.Add(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取文件出错:" + ex.Message);
            }
            return strs;
        }

        #endregion

        #region 创建文件夹

        /// <summary>
        /// 新建目录 上一级必须先存在
        /// </summary>
        /// <param name="dirName">服务器下的相对路径</param>
        public static void MakeDir(string dirName)
        {
            try
            {
                string uri = Path.Combine(ftpServer, dirName);
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.UseBinary = true;
                reqFTP.KeepAlive = false;
                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);
            }
        }

        #endregion

        #region 删除文件夹

        /// <summary>
        /// 删除目录 上一级必须先存在
        /// </summary>
        /// <param name="dirName">服务器下的相对路径</param>
        public static void DelDir(string dirName)
        {
            try
            {
                string uri = Path.Combine(ftpServer, dirName);
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("删除目录出错:" + ex.Message);
            }
        }

        #endregion

        #region 获取文件夹列表

        /// <summary>
        /// 从ftp服务器上获得文件夹列表
        /// </summary>
        /// <param name="RequedstPath">服务器下的相对路径</param>
        /// <returns></returns>
        public static List<string> GetDirctory(string RequedstPath)
        {
            List<string> strs = new List<string>();
            try
            {
                string uri = Path.Combine(ftpServer, RequedstPath);
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                reqFTP.KeepAlive = false;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string line = reader.ReadLine();
                while (line != null)
                {
                    if (line.Contains("<DIR>"))
                    {
                        string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
                        strs.Add(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取目录出错:" + ex.Message);
            }
            return strs;
        }

        #endregion

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

若行若冲

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

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

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

打赏作者

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

抵扣说明:

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

余额充值