设为首页 收藏本站
查看: 1088|回复: 0

[经验分享] C# 中比较好用的ftp操作类,值得学习

[复制链接]

尚未签到

发表于 2015-11-6 09:44:01 | 显示全部楼层 |阅读模式
  FTP具体操作过程的类
  using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Collections;
using System.IO.Compression;


using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Runtime.Serialization;
using Microsoft.Win32;


namespace FTP
{
    class BaseClass
    {
        public class Win32
        {
            public const uint SHGFI_ICON = 0x100;
            public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
            public const uint SHGFI_SMALLICON = 0x1; // 'Small icon
            [DllImport("shell32.dll", EntryPoint = "ExtractIcon")]
            public static extern int ExtractIcon(IntPtr hInst, string lpFileName, int nIndex);
            [DllImport("shell32.dll", EntryPoint = "SHGetFileInfo")]
            public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttribute, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint Flags);
            [DllImport("User32.dll", EntryPoint = "DestroyIcon")]
            public static extern int DestroyIcon(IntPtr hIcon);
            [DllImport("shell32.dll")]
            public static extern uint ExtractIconEx(string lpszFile, int nIconIndex, int[] phiconLarge, int[] phiconSmall, uint nIcons);
            [StructLayout(LayoutKind.Sequential)]
            public struct SHFILEINFO
            {
                public IntPtr hIcon;
                public IntPtr iIcon;
                public uint dwAttributes;
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
                public string szDisplayName;
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
                public string szTypeName;
            }
        }


        #region  获取服务器图标
        /// 给出文件扩展名(.*),返回相应图标
        /// 若不以"."开头则返回文件夹的图标。
        public Icon GetIconByFileType(string fileType,bool isLarge)
        {
            if(fileType == null || fileType.Equals(string.Empty)) return null;
            RegistryKey regVersion = null;
            string regFileType = null;
            string regIconString = null;
            string systemDirectory = Environment.SystemDirectory + "\\";
            if(fileType[0] == '.')
            {
                //读系统注册表中文件类型信息
                regVersion = Registry.ClassesRoot.OpenSubKey(fileType, true);
                if(regVersion != null)
                {
                    regFileType = regVersion.GetValue("") as string;
                    regVersion.Close();
                    regVersion = Registry.ClassesRoot.OpenSubKey(regFileType + @"\DefaultIcon" , true);
                    if(regVersion != null)
                    {
                        regIconString = regVersion.GetValue("") as string;
                        regVersion.Close();
                    }
                }
                if(regIconString == null)
                {
                    //没有读取到文件类型注册信息,指定为未知文件类型的图标
                    regIconString = systemDirectory +"shell32.dll,0";
                }
            }
            else
            {
                //直接指定为文件夹图标
                regIconString = systemDirectory +"shell32.dll,3";
            }
            string[] fileIcon = regIconString.Split(new char[]{','});
            if(fileIcon.Length != 2)
            {
                //系统注册表中注册的标图不能直接提取,则返回可执行文件的通用图标
                fileIcon = new string[]{systemDirectory +"shell32.dll","2"};
            }
            Icon resultIcon = null;
            try
            {
                //调用API方法读取图标
                int[] phiconLarge = new int[1];
                int[] phiconSmall = new int[1];
                uint count = Win32.ExtractIconEx(fileIcon[0],Int32.Parse(fileIcon[1]),phiconLarge,phiconSmall,1);
                IntPtr IconHnd = new IntPtr(isLarge?phiconLarge[0]:phiconSmall[0]);
                resultIcon = Icon.FromHandle(IconHnd);
            }


            catch
            {
                fileIcon = new string[] { systemDirectory + "shell32.dll", "2" };
                                //调用API方法读取图标
                int[] phiconLarge = new int[1];
                int[] phiconSmall = new int[1];
                uint count = Win32.ExtractIconEx(fileIcon[0],Int32.Parse(fileIcon[1]),phiconLarge,phiconSmall,1);
                IntPtr IconHnd = new IntPtr(isLarge?phiconLarge[0]:phiconSmall[0]);
                resultIcon = Icon.FromHandle(IconHnd);
            }
            return resultIcon;
        }
        #endregion




        #region  文件夹的复制
        /// <summary>
        /// 文件夹的复制
        /// </summary>
        /// <param Ddir=&quot;string&quot;>要复制的目的路径</param>
        /// <param Sdir=&quot;string&quot;>要复制的原路径</param>
        public void Files_Copy(string Ddir, string Sdir)
        {
            DirectoryInfo dir = new DirectoryInfo(Sdir);
            string SbuDir = Ddir;
            try
            {
                if (!dir.Exists)//判断所指的文件或文件夹是否存在
                {
                    return;
                }
                DirectoryInfo dirD = dir as DirectoryInfo;//如果给定参数不是文件夹则退出
                string UpDir = UpAndDown_Dir(Ddir);
                if (dirD == null)//判断文件夹是否为空
                {
                    Directory.CreateDirectory(UpDir &#43; &quot;\\&quot; &#43; dirD.Name);//如果为空,创建文件夹并退出
                    return;
                }
                else
                {
                    Directory.CreateDirectory(UpDir &#43; &quot;\\&quot; &#43; dirD.Name);
                }
                SbuDir = UpDir &#43; &quot;\\&quot; &#43; dirD.Name &#43; &quot;\\&quot;;
                FileSystemInfo[] files = dirD.GetFileSystemInfos();//获取文件夹中所有文件和文件夹
                //对单个FileSystemInfo进行判断,如果是文件夹则进行递归操作
                foreach (FileSystemInfo FSys in files)
                {
                    FileInfo file = FSys as FileInfo;
                    if (file != null)//如果是文件的话,进行文件的复制操作
                    {
                        FileInfo SFInfo = new FileInfo(file.DirectoryName &#43; &quot;\\&quot; &#43; file.Name);//获取文件所在的原始路径
                        SFInfo.CopyTo(SbuDir &#43; &quot;\\&quot; &#43; file.Name, true);//将文件复制到指定的路径中
                    }
                    else
                    {
                        string pp = FSys.Name;//获取当前搜索到的文件夹名称
                        Files_Copy(SbuDir &#43; FSys.ToString(), Sdir &#43; &quot;\\&quot; &#43; FSys.ToString());//如果是文件,则进行递归调用
                    }
                }
            }
            catch
            {
                MessageBox.Show(&quot;文件制复失败。&quot;);
                return;
            }
        }
        #endregion


        #region  返回上一级目录
        /// <summary>
        /// 返回上一级目录
        /// </summary>
        /// <param dir=&quot;string&quot;>目录</param>
        /// <returns>返回String对象</returns>
        public string UpAndDown_Dir(string dir)
        {
            string Change_dir = &quot;&quot;;
            Change_dir = Directory.GetParent(dir).FullName;
            return Change_dir;
        }
        #endregion




        public void getFTPServerICO(ImageList il,string ftpip,string  user,string  pwd,ListView lv,string path)//获取服务器的图标
        {
            try
            {
                string[] a;
                lv.Items.Clear();
                il.Images.Clear();
                if(path.Length==0)
                    a = GetFileList(ftpip, user, pwd);
                else
                    a= GetFileList(ftpip &#43; &quot;/&quot; &#43; path.Remove(path.LastIndexOf(&quot;/&quot;)), user, pwd);
                if (a != null)
                {


                    for (int i = 0; i < a.Length; i&#43;&#43;)
                    {
                        
                        string[] b = a.ToString().Split(' ');
                        string filename = b[b.Length-1];
                        string filetype=&quot;&quot;;
                        if (a.IndexOf(&quot;DIR&quot;) != -1)
                        {
                            filetype = filename;
                        }
                        else
                        {
                            filetype = filename.Substring(filename.LastIndexOf(&quot;.&quot;), filename.Length - filename.LastIndexOf(&quot;.&quot;));
                        }
                        try
                        {
                            il.Images.Add(GetIconByFileType(filetype, true));
                        }
                        catch (Exception)
                        {
                            il.Images.Add(Properties.Resources.file);
                        }


                        string[] info = new string[4];
                        FileInfo fi = new FileInfo(filename);
                        info[0] = fi.Name;
                        info[1] = GetFileSize(filename, ftpip, user, pwd, path).ToString();
                        if (a.IndexOf(&quot;DIR&quot;) != -1)
                        {
                            info[2] = &quot;&quot;;
                            info[1] = &quot;文件夹&quot;;
                        }
                        else
                        {
                            info[2] = GetFileSize(filename, ftpip, user, pwd, path).ToString();
                            info[1] = fi.Extension.ToString();
                        }
                        ListViewItem item = new ListViewItem(info, i);
                        lv.Items.Add(item);
                    }
                }
            }
            catch{}
        }


        public void listFolders(ToolStripComboBox tscb)//获取本地磁盘目录
        {
            string[] logicdrives = System.IO.Directory.GetLogicalDrives();
            for (int i = 0; i < logicdrives.Length; i&#43;&#43;)
            {
                tscb.Items.Add(logicdrives);
                tscb.SelectedIndex = 0;
            }
        }


        int k = 0;
        public void GOBack(ListView lv,ImageList il,string path)
        {


            if (AllPath.Length != 3)
            {
                string NewPath = AllPath.Remove(AllPath.LastIndexOf(&quot;\\&quot;)).Remove(AllPath.Remove(AllPath.LastIndexOf(&quot;\\&quot;)).LastIndexOf(&quot;\\&quot;)) &#43; &quot;\\&quot;;
                lv.Items.Clear();
                GetListViewItem(NewPath, il, lv);
                AllPath = NewPath;
            }
            else
            {
                if (k == 0)
                {
                    lv.Items.Clear();
                    GetListViewItem(path, il, lv);
                    k&#43;&#43;;
                }
            }
        }
        public string Mpath()
        {
            string path=AllPath;
            return path;
        }


        public static string AllPath = &quot;&quot;;//---------
        public void GetPath(string path, ImageList imglist, ListView lv,int ppath)//-------
        {
                string pp = &quot;&quot;;
                string uu = &quot;&quot;;
                if (ppath == 0)
                {
                    if (AllPath != path)
                    {
                        lv.Items.Clear();
                        AllPath = path;
                        GetListViewItem(AllPath, imglist, lv);
                    }
                }
                else
                {
                    uu = AllPath &#43; path;
                    if (Directory.Exists(uu))
                    {
                        AllPath = AllPath &#43; path &#43; &quot;\\&quot;;
                        pp = AllPath.Substring(0, AllPath.Length - 1);
                        lv.Items.Clear();
                        GetListViewItem(pp, imglist, lv);
                    }
                    else
                    {
                        uu = AllPath &#43; path;
                        System.Diagnostics.Process.Start(uu);
                    }
                }
        }


        public void GetListViewItem(string path, ImageList imglist, ListView lv)//获取指定路径下所有文件及其图标
        {
            lv.Items.Clear();
            Win32.SHFILEINFO shfi = new Win32.SHFILEINFO();
            try
            {
                string[] dirs = Directory.GetDirectories(path);
                string[] files = Directory.GetFiles(path);
                for (int i = 0; i < dirs.Length; i&#43;&#43;)
                {
                    string[] info = new string[4];
                    DirectoryInfo dir = new DirectoryInfo(dirs);
                    if (dir.Name == &quot;RECYCLER&quot; || dir.Name == &quot;RECYCLED&quot; || dir.Name == &quot;Recycled&quot; || dir.Name == &quot;System Volume Information&quot;)
                    { }
                    else
                    {
                        //获得图标
                        Win32.SHGetFileInfo(dirs,
                                            (uint)0x80,
                                            ref shfi,
                                            (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                            (uint)(0x100 | 0x400)); //取得Icon和TypeName
                        //添加图标
                        imglist.Images.Add(dir.Name, (Icon)Icon.FromHandle(shfi.hIcon).Clone());
                        info[0] = dir.Name;
                        info[1] = &quot;&quot;;
                        info[2] = &quot;文件夹&quot;;
                        info[3] = dir.LastWriteTime.ToString();
                        ListViewItem item = new ListViewItem(info, dir.Name);
                        lv.Items.Add(item);
                        //销毁图标
                        Win32.DestroyIcon(shfi.hIcon);
                    }
                }
                for (int i = 0; i < files.Length; i&#43;&#43;)
                {
                    string[] info = new string[4];
                    FileInfo fi = new FileInfo(files);
                    string Filetype = fi.Name.Substring(fi.Name.LastIndexOf(&quot;.&quot;)&#43;1,fi.Name.Length- fi.Name.LastIndexOf(&quot;.&quot;) -1);
                    string newtype=Filetype.ToLower();
                    if (newtype == &quot;sys&quot; || newtype == &quot;ini&quot; || newtype == &quot;bin&quot; || newtype == &quot;log&quot; || newtype == &quot;com&quot; || newtype == &quot;bat&quot; || newtype == &quot;db&quot;)
                    { }
                    else
                    {




                        //获得图标
                        Win32.SHGetFileInfo(files,
                                            (uint)0x80,
                                            ref shfi,
                                            (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                            (uint)(0x100 | 0x400)); //取得Icon和TypeName
                        //添加图标
                        imglist.Images.Add(fi.Name, (Icon)Icon.FromHandle(shfi.hIcon).Clone());
                        info[0] = fi.Name;
                        info[1] = fi.Length.ToString();
                        info[2] = fi.Extension.ToString();
                        info[3] = fi.LastWriteTime.ToString();
                        ListViewItem item = new ListViewItem(info, fi.Name);
                        lv.Items.Add(item);
                        //销毁图标
                        Win32.DestroyIcon(shfi.hIcon);
                    }
                }
            }
            catch
            {
            }
        }


        FtpWebRequest reqFTP;
        public bool CheckFtp(string DomainName, string FtpUserName, string FtpUserPwd)//验证登录用户是否合法
        {
            bool ResultValue = true;
            try
            {
                FtpWebRequest ftprequest = (FtpWebRequest)WebRequest.Create(&quot;ftp://&quot; &#43; DomainName);//创建FtpWebRequest对象
                ftprequest.Credentials = new NetworkCredential(FtpUserName, FtpUserPwd);//设置FTP登陆信息
                ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;//发送一个请求命令
                FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();//响应一个请求
                ftpResponse.Close();//关闭请求
            }
            catch
            {
                ResultValue = false;
            }
            return ResultValue;
        }


        public long GetFileSize(string filename, string ftpserver,string ftpUserID, string ftpPassword,string path)
        {
            long filesize = 0;
            try
            {
                FileInfo fi = new FileInfo(filename);
                string uri;
                if(path.Length==0)
                    uri = &quot;ftp://&quot; &#43; ftpserver &#43; &quot;/&quot; &#43; fi.Name;
                else
                    uri = &quot;ftp://&quot; &#43; ftpserver &#43; &quot;/&quot; &#43;path&#43; fi.Name;
                Connect(uri, ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                filesize = response.ContentLength;
                return filesize;
            }
            catch
            {
                return 0;
            }
        }


        //从ftp服务器上获得文件列表


        public string[] GetFileList(string ftpServerIP, string ftpUserID, string ftpPassword)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(&quot;ftp://&quot; &#43; ftpServerIP));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(&quot;GB2312&quot;));
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append(&quot;\n&quot;);
                    line = reader.ReadLine();
                    
                }
                result.Remove(result.ToString().LastIndexOf('\n'), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch
            {
                downloadFiles = null;
                return downloadFiles;
            }
        }


        public string[] GetFileListAll(string ftpServerIP, string ftpUserID, string ftpPassword,string filename,string path)//指定路径的文件列表
        {
            if (path == null)
                path = &quot;&quot;;
            if (path.Length == 0)
            {
                string[] downloadFiles;
                StringBuilder result = new StringBuilder();
                FtpWebRequest reqFTP;
                try
                {
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(&quot;ftp://&quot; &#43; ftpServerIP &#43; &quot;/&quot; &#43; filename));
                    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.GetEncoding(&quot;GB2312&quot;));


                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        result.Append(line);
                        result.Append(&quot;\n&quot;);
                        line = reader.ReadLine();
                    }
                    result.Remove(result.ToString().LastIndexOf('\n'), 1);
                    reader.Close();
                    response.Close();
                    return result.ToString().Split('\n');
                }
                catch
                {
                    downloadFiles = null;
                    return downloadFiles;
                }
            }
            else
            {
                string[] downloadFiles;
                StringBuilder result = new StringBuilder();
                FtpWebRequest reqFTP;
                try
                {
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(&quot;ftp://&quot; &#43; ftpServerIP &#43; &quot;/&quot; &#43;path&#43; filename));
                    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.GetEncoding(&quot;GB2312&quot;));


                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        result.Append(line);
                        result.Append(&quot;\n&quot;);
                        line = reader.ReadLine();
                    }
                    result.Remove(result.ToString().LastIndexOf('\n'), 1);
                    reader.Close();
                    response.Close();
                    return result.ToString().Split('\n');
                }
                catch
                {
                    downloadFiles = null;
                    return downloadFiles;
                }
            }
        }


        //去除空&#26684;
        private string QCKG(string str)
        {
            string a = &quot;&quot;;
            CharEnumerator CEnumerator = str.GetEnumerator();
            while (CEnumerator.MoveNext())
            {
                byte[] array = new byte[1];
                array = System.Text.Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());
                int asciicode = (short)(array[0]);
                if (asciicode != 32)
                {
                    a &#43;= CEnumerator.Current.ToString();
                }
            }
            string sdate = System.DateTime.Now.Year.ToString() &#43; System.DateTime.Now.Month.ToString() &#43; System.DateTime.Now.Day.ToString() &#43; System.DateTime.Now.Hour.ToString()
                &#43; System.DateTime.Now.Minute.ToString() &#43; System.DateTime.Now.Second.ToString() &#43; System.DateTime.Now.Millisecond.ToString();
            return a.Split('.')[a.Split('.').Length - 2] &#43; &quot;.&quot; &#43; a.Split('.')[a.Split('.').Length - 1];
            //return sdate &#43; &quot;.&quot; &#43; a.Split('.')[a.Split('.').Length - 1];
        }


        public string newFileName;

        //断点续传
        public bool Upload(string filename, string ftpServerIP, string ftpUserID, string ftpPassword, ToolStripProgressBar pb,string path)
        {
            if (path == null)
                path = &quot;&quot;;
            bool success = true;
            FileInfo fileInf = new FileInfo(filename);
            long allbye = (long)fileInf.Length;
            if (fileInf.Name.IndexOf(&quot;#&quot;) == -1)
            {
                newFileName = QCKG(fileInf.Name);
            }
            else
            {
                newFileName = fileInf.Name.Replace(&quot;#&quot;, &quot;#&quot;);
                newFileName = QCKG(newFileName);
            }
            long startfilesize = GetFileSize(newFileName, ftpServerIP, ftpUserID, ftpPassword, path);
            if (startfilesize >= allbye)
            {
                return false;
            }
            //startfilesize=0;
            long startbye = startfilesize;
            pb.Maximum = Convert.ToInt32(allbye);


            pb.Minimum = Convert.ToInt32(startfilesize);
            
            string uri;
            if (path.Length == 0)
                uri = &quot;ftp://&quot; &#43; ftpServerIP &#43; &quot;/&quot; &#43; newFileName;
            else
                uri = &quot;ftp://&quot; &#43; ftpServerIP &#43; &quot;/&quot; &#43; path &#43; newFileName;
            FtpWebRequest reqFTP;
            // 根据uri创建FtpWebRequest对象
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            // ftp用户名和密码
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            // 默认为true,连接不会被关闭
            // 在一个命令之后被执行
            reqFTP.KeepAlive = false;
            // 指定执行什么命令
            reqFTP.Method = WebRequestMethods.Ftp.AppendFile;
            // 指定数据传输类型
            reqFTP.UseBinary = true;
            // 上传文件时通知服务器文件的大小
            reqFTP.ContentLength = fileInf.Length;
            int buffLength = 2048;// 缓冲大小设置为2kb
            byte[] buff = new byte[buffLength];
            // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
            FileStream fs= fileInf.OpenRead();
            try
            {
                // 把上传的文件写入流
                Stream strm = reqFTP.GetRequestStream();
                // 每次读文件流的2kb   
                fs.Seek(startfilesize, 0);
                int contentLen = fs.Read(buff, 0, buffLength);
                // 流内容没有结束
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                    startbye &#43;= contentLen;
                    pb.Value = Convert.ToInt32(startbye);
                }
                // 关闭两个流
                strm.Close();
                fs.Close();
             }
             catch
             {
                 success = false;
             }
             return success;
        }


        public void Connect(String path, string ftpUserID, string ftpPassword)//连接ftp
        {
            // 根据uri创建FtpWebRequest对象
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
            // 指定数据传输类型
            reqFTP.UseBinary = true;
            // ftp用户名和密码
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        }


        //删除文件


        public void DeleteFileName(string fileName, string ftpServerIP, string ftpUserID, string ftpPassword,string path)
        {
           try
           {
               string uri;
               if(path.Length==0)
                   uri=&quot;ftp://&quot; &#43; ftpServerIP &#43; &quot;/&quot; &#43; fileName;
               else
                   uri = &quot;ftp://&quot; &#43; ftpServerIP &#43; &quot;/&quot; &#43; path &#43; fileName;
               // 根据uri创建FtpWebRequest对象
               reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
               // 指定数据传输类型
               reqFTP.UseBinary = true;
               // ftp用户名和密码
               reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
               // 默认为true,连接不会被关闭
               // 在一个命令之后被执行
               reqFTP.KeepAlive = false;
               // 指定执行什么命令
               reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
               FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
               response.Close();
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.Message, &quot;删除错误&quot;);
           }
        }


        //下载文件


        public bool Download(string filePath, string fileName, string ftpServerIP, string ftpUserID, string ftpPassword,string path)
        {
            bool check = true;
            FtpWebRequest reqFTP;
            string uri;
            if (path.Length == 0)
                uri = &quot;ftp://&quot; &#43; ftpServerIP &#43; &quot;/&quot; &#43; fileName;
            else
                uri = &quot;ftp://&quot; &#43; ftpServerIP &#43; &quot;/&quot; &#43; path &#43; fileName;
            try
            {
                FileStream outputStream = new FileStream(filePath &#43; &quot;\\&quot; &#43; fileName, FileMode.Create);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                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
            {
                check = false;
            }
            return check;
        }
      
        //创建目录


        public void MakeDir(string dirName, string ftpServerIP,string ftpUserID, string ftpPassword)
        {
            try
            {
                string uri = &quot;ftp://&quot; &#43; ftpServerIP &#43;&quot;/&quot;&#43; dirName;
                Connect(uri, ftpUserID, ftpPassword);//连接      
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch{}
        }


        //删除目录


        public void delDir(string dirName, string ftpServerIP, string ftpUserID, string ftpPassword)
        {
             try
             {
                 string uri = &quot;ftp://&quot; &#43; ftpServerIP &#43; &quot;/&quot; &#43; dirName;
                 Connect(uri, ftpUserID, ftpPassword);//连接      
                 reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;//向服务器发送删除文件夹的命令
                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                 response.Close();
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message);
             }
        }
         
        //下载文件夹


        public string[] GetFTPList(string ftpServerIP, string ftpUserID, string ftpPassword, string path)//指定路径的文件列表
        {
            if (path == null)
            path = &quot;&quot;;
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(&quot;ftp://&quot; &#43; ftpServerIP &#43; &quot;/&quot; &#43; path.Remove(path.LastIndexOf(&quot;/&quot;))));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(&quot;GB2312&quot;));


                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append(&quot;\n&quot;);
                    line = reader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf('\n'), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch
            {
                downloadFiles = null;
                return downloadFiles;
            }
        }
    }
}

         版权声明:本文为博主原创文章,未经博主允许不得转载。 博客列表: http://blog.iyunv.com/chr23899

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-135751-1-1.html 上篇帖子: GruntJs之FTP上传文件 下篇帖子: 错误总结——FTP 550 Permission denied
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表