语言吧技术网欢迎您投稿,程序员的世界我懂你!=====>点此登录投搞
当前位置: 首页 >>ASP.NET >>C#基础 >>C# FTP操作类

C# FTP操作类

2019/1/9 11:10:54 0人评论 195次 作者:Qiu_SmileToLife

整理简化了下C#的ftp操作,方便使用1.异常方法委托,通过Lamda委托统一处理异常,方便改写。加了个委托方便控制异常输出 2.ftp的删除需要递归查找所有目录存入list,然后根据 level倒序排序,从最末级开始遍历删除 3.其他的整个目录操作都是同上…

C#开发-FTP操作方法整理


1.整理简化了下C#的ftp操作,方便使用


1.支持创建多级目录 

2.批量删除 

3.整个目录上传 

4.整个目录删除 

5.整个目录下载 

2.调用方法展示,


var ftp = new FtpHelper(“10.136.12.11”, “qdx1213123”, “123ddddf”);//初始化ftp,创建ftp对象 

ftp.DelAll(“test”);//删除ftptest目录及其目录下的所有文件 

ftp.UploadAllFile(“F:\test\wms.zip”);//上传单个文件到指定目录 

ftp.UploadAllFile(“F:\test”);//将本地test目录的所有文件上传 

ftp.DownloadFile(“test\wms.zip”, “F:\test1”);//下载单个目录 

ftp.DownloadAllFile(“test”, “F:\test1”);//批量下载整个目录 

ftp.MakeDir(“aaa\bbb\ccc\ddd”);//创建多级目录


3.FtpHelper 代码。


1.异常方法委托,通过Lamda委托统一处理异常,方便改写。加了个委托方便控制异常输出 

2.ftp的删除需要递归查找所有目录存入list,然后根据 level倒序排序,从最末级开始遍历删除 

3.其他的整个目录操作都是同上


using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Net; 

using System.IO;


namespace MyStuday 

/// 

/// ftp帮助类 

/// 

public class FtpHelper 

private string ftpHostIP { get; set; } 

private string username { get; set; } 

private string password { get; set; } 

private string ftpURI { get { return $@”ftp://{ftpHostIP}/”; } }


    /// <summary>

    /// 初始化ftp参数

    /// </summary>

    /// <param name="ftpHostIP">ftp主机IP</param>

    /// <param name="username">ftp账户</param>

    /// <param name="password">ftp密码</param>

    public FtpHelper(string ftpHostIP, string username, string password)

    {

        this.ftpHostIP = ftpHostIP;

        this.username = username;

        this.password = password;

    }


    /// <summary>

    /// 异常方法委托,通过Lamda委托统一处理异常,方便改写

    /// </summary>

    /// <param name="method">当前执行的方法</param>

    /// <param name="action"></param>

    /// <returns></returns>

    private bool MethodInvoke(string method, Action action)

    {

        if (action != null)

        {

            try

            {

                action();

                //Logger.Write2File($@"FtpHelper.{method}:执行成功");

                FluentConsole.Magenta.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行成功");

                return true;

            }

            catch (Exception ex)

            {

                FluentConsole.Red.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行失败:\n {ex}");

                // Logger.Write2File(FtpHelper({ftpHostIP},{username},{password}).{method}:执行失败 \r\n{ex}");

                return false;

            }

        }

        else

        {

            return false;

        }

    }


    /// <summary>

    /// 异常方法委托,通过Lamda委托统一处理异常,方便改写

    /// </summary>

    /// </summary>

    /// <typeparam name="T"></typeparam>

    /// <param name="method"></param>

    /// <param name="func"></param>

    /// <returns></returns>

    private T MethodInvoke<T>(string method, Func<T> func)

    {

        if (func != null)

        {

            try

            {

                //FluentConsole.Magenta.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行成功");

                //Logger.Write2File($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行成功");

                return func();

            }

            catch (Exception ex)

            {

                //FluentConsole.Red.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行失败:").Line(ex);

                // Logger.Write2File($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行失败 \r\n{ex}");

                return default(T);

            }

        }

        else

        {

            return default(T);

        }

    }

    private FtpWebRequest GetRequest(string URI)

    {

        //根据服务器信息FtpWebRequest创建类的对象

        FtpWebRequest result = (FtpWebRequest)WebRequest.Create(URI);

        result.Credentials = new NetworkCredential(username, password);

        result.KeepAlive = false;

        result.UsePassive = false;

        result.UseBinary = true;

        return result;

    }


    /// <summary> 上传文件</summary>

    /// <param name="filePath">需要上传的文件路径</param>

    /// <param name="dirName">目标路径</param>

    public bool UploadFile(string filePath, string dirName = "")

    {

        FileInfo fileInfo = new FileInfo(filePath);

        if (dirName != "") MakeDir(dirName);//检查文件目录,不存在就自动创建

        string uri = Path.Combine(ftpURI, dirName, fileInfo.Name);

        return MethodInvoke($@"uploadFile({filePath},{dirName})", () =>

        {

            FtpWebRequest ftp = GetRequest(uri);

            ftp.Method = WebRequestMethods.Ftp.UploadFile;

            ftp.ContentLength = fileInfo.Length;

            int buffLength = 2048;

            byte[] buff = new byte[buffLength];

            int contentLen;

            using (FileStream fs = fileInfo.OpenRead())

            {

                using (Stream strm = ftp.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();

            }

        });

    }


    /// <summary>

    /// 从一个目录将其内容复制到另一目录

    /// </summary>

    /// <param name="localDir">源目录</param>

    /// <param name="DirName">目标目录</param>

    public void UploadAllFile(string localDir, string DirName = "")

    {

        string localDirName = string.Empty;

        int targIndex = localDir.LastIndexOf("\\");

        if (targIndex > -1 && targIndex != (localDir.IndexOf(":\\") + 1))

            localDirName = localDir.Substring(0, targIndex);

        localDirName = localDir.Substring(targIndex + 1);

        string newDir = Path.Combine(DirName, localDirName);

        MethodInvoke($@"UploadAllFile({localDir},{DirName})", () =>

        {

            MakeDir(newDir);

            DirectoryInfo directoryInfo = new DirectoryInfo(localDir);

            FileInfo[] files = directoryInfo.GetFiles();

            //复制所有文件  

            foreach (FileInfo file in files)

            {

                UploadFile(file.FullName, newDir);

            }

            //最后复制目录  

            DirectoryInfo[] directoryInfoArray = directoryInfo.GetDirectories();

            foreach (DirectoryInfo dir in directoryInfoArray)

            {

                UploadAllFile(Path.Combine(localDir, dir.Name), newDir);

            }

        });

    }


    /// <summary> 

    /// 删除单个文件

    /// </summary>

    /// <param name="filePath"></param>

    public bool DelFile(string filePath)

    {

        string uri = Path.Combine(ftpURI, filePath);

        return MethodInvoke($@"DelFile({filePath})", () =>

        {

            FtpWebRequest ftp = GetRequest(uri);

            ftp.Method = WebRequestMethods.Ftp.DeleteFile;

            FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();

            response.Close();

        });

    }


    /// <summary> 

    /// 删除最末及空目录

    /// </summary>

    /// <param name="dirName"></param>

    private bool DelDir(string dirName)

    {

        string uri = Path.Combine(ftpURI, dirName);

        return MethodInvoke($@"DelDir({dirName})", () =>

        {

            FtpWebRequest ftp = GetRequest(uri);

            ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;

            FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();

            response.Close();

        });

    }


    /// <summary> 删除目录或者其目录下所有的文件 </summary>

    /// <param name="dirName">目录名称</param>

    /// <param name="ifDelSub">是否删除目录下所有的文件</param>

    public bool DelAll(string dirName)

    {

        var list = GetAllFtpFile(new List<ActFile>(),dirName);

        if (list == null)   return  DelDir(dirName);

        if (list.Count==0)  return  DelDir(dirName);//删除当前目录

        var newlist = list.OrderByDescending(x => x.level);

        foreach (var item in newlist)

        {

            FluentConsole.Yellow.Line($@"level:{item.level},isDir:{item.isDir},path:{item.path}");

        }

        string uri = Path.Combine(ftpURI, dirName);

        return MethodInvoke($@"DelAll({dirName})", () =>

        {

            foreach (var item in newlist)

            {

                if (item.isDir)//判断是目录调用目录的删除方法

                    DelDir(item.path);

                else

                    DelFile(item.path);

            }

            DelDir(dirName);//删除当前目录

            return true;

        });

    }


    /// <summary>

    /// 下载单个文件

    /// </summary>

    /// <param name="ftpFilePath">从ftp要下载的文件路径</param>

    /// <param name="localDir">下载至本地路径</param>

    /// <param name="filename">文件名</param>

    public bool DownloadFile(string ftpFilePath, string saveDir)

    {

        string filename = ftpFilePath.Substring(ftpFilePath.LastIndexOf("\\") + 1);

        string tmpname = Guid.NewGuid().ToString();

        string uri = Path.Combine(ftpURI, ftpFilePath);

        return MethodInvoke($@"DownloadFile({ftpFilePath},{saveDir},{filename})", () =>

        {

            if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);

            FtpWebRequest ftp = GetRequest(uri);

            ftp.Method = WebRequestMethods.Ftp.DownloadFile;

            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())

            {

                using (Stream responseStream = response.GetResponseStream())

                {

                    using (FileStream fs = new FileStream(Path.Combine(saveDir, filename), FileMode.CreateNew))

                    {

                        byte[] buffer = new byte[2048];

                        int read = 0;

                        do

                        {

                            read = responseStream.Read(buffer, 0, buffer.Length);

                            fs.Write(buffer, 0, read);

                        } while (!(read == 0));

                        responseStream.Close();

                        fs.Flush();

                        fs.Close();

                    }

                    responseStream.Close();

                }

                response.Close();

            }

        });

    }


    /// <summary>    

    /// 从FTP下载整个文件夹    

    /// </summary>    

    /// <param name="dirName">FTP文件夹路径</param>    

    /// <param name="saveDir">保存的本地文件夹路径</param>    

    public void DownloadAllFile(string dirName, string saveDir)

    {

        MethodInvoke($@"DownloadAllFile({dirName},{saveDir})", () =>

        {

            List<ActFile> files = GetFtpFile(dirName);

            if (!Directory.Exists(saveDir))

            {

                Directory.CreateDirectory(saveDir);

            }

            foreach (var f in files)

            {

                if (f.isDir) //文件夹,递归查询  

                {

                    DownloadAllFile(Path.Combine(dirName,f.name), Path.Combine(saveDir ,f.name));

                }

                else //文件,直接下载  

                {

                    DownloadFile(Path.Combine(dirName,f.name), saveDir);

                }

            }

        });

    }


    /// <summary>

    /// 获取当前目录下的目录及文件

    /// </summary>

    /// param name="ftpfileList"></param>

    /// <param name="dirName"></param>

    /// <returns></returns>

    public List<ActFile> GetFtpFile(string dirName,int ilevel = 0)

    {

        var ftpfileList = new List<ActFile>();

        string uri = Path.Combine(ftpURI, dirName);

        return MethodInvoke($@"GetFtpFile({dirName})", () =>

        {

            var a = new List<List<string>>();

            FtpWebRequest ftp = GetRequest(uri);

            ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

            Stream stream = ftp.GetResponse().GetResponseStream();

            using (StreamReader sr = new StreamReader(stream))

            {

                string line = sr.ReadLine();

                while (!string.IsNullOrEmpty(line))

                {

                    ftpfileList.Add(new ActFile { isDir = line.IndexOf("<DIR>") > -1, name = line.Substring(39).Trim(), path = Path.Combine(dirName, line.Substring(39).Trim()), level= ilevel });

                    line = sr.ReadLine();

                }

                sr.Close();

            }

            return ftpfileList;

        });



    }


    /// <summary>

    /// 获取FTP目录下的所有目录及文件包括其子目录和子文件

    /// </summary>

    /// param name="result"></param>

    /// <param name="dirName"></param>

    /// <returns></returns>

    public List<ActFile> GetAllFtpFile(List<ActFile> result,string dirName, int level = 0)

    {

        var ftpfileList = new List<ActFile>();

        string uri = Path.Combine(ftpURI, dirName);

        return MethodInvoke($@"GetAllFtpFile({dirName})", () =>

        {

             ftpfileList = GetFtpFile(dirName, level);

            result.AddRange(ftpfileList);

            var newlist = ftpfileList.Where(x => x.isDir).ToList();

            foreach (var item in newlist)

            {

                GetAllFtpFile(result,item.path, level+1);

            }

            return result;

        });


    }


    /// <summary>

    /// 检查目录是否存在

    /// </summary>

    /// <param name="dirName"></param>

    /// <param name="currentDir"></param>

    /// <returns></returns>

    public bool CheckDir(string dirName, string currentDir = "")

    {

        string uri = Path.Combine(ftpURI, currentDir);

        return MethodInvoke($@"CheckDir({dirName}{currentDir})", () =>

        {

            FtpWebRequest ftp = GetRequest(uri);

            ftp.UseBinary = true;

            ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

            Stream stream = ftp.GetResponse().GetResponseStream();

            using (StreamReader sr = new StreamReader(stream))

            {

                string line = sr.ReadLine();

                while (!string.IsNullOrEmpty(line))

                {

                    if (line.IndexOf("<DIR>") > -1)

                    {

                        if (line.Substring(39).Trim() == dirName)

                            return true;

                    }

                    line = sr.ReadLine();

                }

                sr.Close();

            }

            stream.Close();

            return false;

        });


    }


    ///  </summary>

    /// 在ftp服务器上创建指定目录,父目录不存在则创建

    /// </summary>

    /// <param name="dirName">创建的目录名称</param>

    public bool MakeDir(string dirName)

    {

        var dirs = dirName.Split('\\').ToList();//针对多级目录分割

        string currentDir = string.Empty;

        return MethodInvoke($@"MakeDir({dirName})", () =>

        {

            foreach (var dir in dirs)

            {

                if (!CheckDir(dir, currentDir))//检查目录不存在则创建

                {

                    currentDir = Path.Combine(currentDir, dir);

                    string uri = Path.Combine(ftpURI, currentDir);

                    FtpWebRequest ftp = GetRequest(uri);

                    ftp.Method = WebRequestMethods.Ftp.MakeDirectory;

                    FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();

                    response.Close();

                }

                else

                {

                    currentDir = Path.Combine(currentDir, dir);

                }

            }


        });


    }


    /// <summary>文件重命名 </summary>

    /// <param name="currentFilename">当前名称</param>

    /// <param name="newFilename">重命名名称</param>

    /// <param name="currentFilename">所在的目录</param>

    public bool Rename(string currentFilename, string newFilename, string dirName = "")

    {

        string uri = Path.Combine(ftpURI, dirName, currentFilename);

        return MethodInvoke($@"Rename({currentFilename},{newFilename},{dirName})", () =>

        {

            FtpWebRequest ftp = GetRequest(uri);

            ftp.Method = WebRequestMethods.Ftp.Rename;

            ftp.RenameTo = newFilename;

            FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();

            response.Close();

        });

    }

}


public class ActFile

{

    public int level { get; set; } = 0;

    public bool isDir { get; set; }

    public string name { get; set; }

    public string path { get; set; } = "";

}


==================================

/////调用开始

using System; 

using System.Collections.Generic; 

using System.Text; 

using System.IO; 

using System.Net; 

using System.Globalization; 

namespace FtpTest1 

public class FtpWeb 

string ftpServerIP; 

string ftpRemotePath; 

string ftpUserID; 

string ftpPassword; 

string ftpURI; 

/// 

/// 连接FTP 

/// 

/// FTP连接地址 

/// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录 

/// 用户名 

/// 密码 

public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword) 

ftpServerIP = FtpServerIP; 

ftpRemotePath = FtpRemotePath; 

ftpUserID = FtpUserID; 

ftpPassword = FtpPassword; 

ftpURI = “ftp://” + ftpServerIP + “/” ; 

static void Main() { 

//string file = “c:\aq3.gifa”; 

//FileInfo fileInf = new FileInfo(file); 

//if (!fileInf.Exists) 

//{ 

// Console.WriteLine(file + ” no exists”); 

//} 

//else { 

// Console.WriteLine(“yes”); 

//} 

//Console.ReadLine(); 

FtpWeb fw = new FtpWeb(“121.11.65.10”, “”, “aa1”, “aa”); 

string[] filePaths = { “c:\aq3.gif1”, “c:\aq2.gif1”, “c:\bsmain_runtime.log” }; 

Console.WriteLine(fw.UploadFile(filePaths)); 

Console.ReadLine(); 

//上传文件 

public string UploadFile( string[] filePaths ) { 

StringBuilder sb = new StringBuilder(); 

if ( filePaths != null && filePaths.Length > 0 ){ 

foreach( var file in filePaths ){ 

sb.Append(Upload( file )); 

return sb.ToString(); 

/// 

/// 上传文件 

/// 

/// 

private string Upload(string filename) 

FileInfo fileInf = new FileInfo(filename); 

if ( !fileInf.Exists ){ 

return filename + ” 不存在!\n”; 

string uri = ftpURI + fileInf.Name; 

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.UsePassive = false; //选择主动还是被动模式 

//Entering Passive Mode 

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) 

return “同步 “+filename+”时连接不上服务器!\n”; 

//Insert_Standard_ErrorLog.Insert(“FtpWeb”, “Upload Error –> ” + ex.Message); 

return “”; 

/// 

/// 下载 

/// 

/// 

/// 

public void Download(string filePath, string fileName) 

FtpWebRequest reqFTP; 

try 

FileStream outputStream = new FileStream(filePath + “\” + fileName, FileMode.Create); 

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName)); 

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) 

Insert_Standard_ErrorLog.Insert(“FtpWeb”, “Download Error –> ” + ex.Message); 

/// 

/// 删除文件 

/// 

/// 

public void Delete(string fileName) 

try 

string uri = ftpURI + fileName; 

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) 

Insert_Standard_ErrorLog.Insert(“FtpWeb”, “Delete Error –> ” + ex.Message + ” 文件名:” + fileName); 

/// 

/// 获取当前目录下明细(包含文件和文件夹) 

/// 

/// 

public string[] GetFilesDetailList() 

string[] downloadFiles; 

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) 

downloadFiles = null; 

Insert_Standard_ErrorLog.Insert(“FtpWeb”, “GetFilesDetailList Error –> ” + ex.Message); 

return downloadFiles; 

/// 

/// 获取当前目录下文件列表(仅文件) 

/// 

/// 

public string[] GetFileList(string mask) 

string[] downloadFiles; 

StringBuilder result = new StringBuilder(); 

FtpWebRequest reqFTP; 

try 

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI)); 

reqFTP.UseBinary = true; 

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 

reqFTP.Method = WebRequestMethods.Ftp.ListDirectory; 

WebResponse response = reqFTP.GetResponse(); 

StreamReader reader = new StreamReader(response.GetResponseStream()); 

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) 文件不可用(例如,未找到文件,无法访问文件)。”) 

Insert_Standard_ErrorLog.Insert(“FtpWeb”, “GetFileList Error –> ” + ex.Message.ToString()); 

return downloadFiles; 

/// 

/// 获取当前目录下所有的文件夹列表(仅文件夹) 

/// 

/// 

public string[] GetDirectoryList() 

string[] drectory = GetFilesDetailList(); 

string m = string.Empty; 

foreach (string str in drectory) 

if (str.Trim().Substring(0, 1).ToUpper() == “D”) 

m += str.Substring(54).Trim() + “\n”; 

char[] n = new char[] { ‘\n’ }; 

return m.Split(n); 

/// 

/// 判断当前目录下指定的子目录是否存在 

/// 

/// 指定的目录名 

public bool DirectoryExist(string RemoteDirectoryName) 

string[] dirList = GetDirectoryList(); 

foreach (string str in dirList) 

if (str.Trim() == RemoteDirectoryName.Trim()) 

return true; 

return false; 

/// 

/// 判断当前目录下指定的文件是否存在 

/// 

/// 远程文件名 

public bool FileExist(string RemoteFileName) 

string[] fileList = GetFileList(“.“); 

foreach (string str in fileList) 

if (str.Trim() == RemoteFileName.Trim()) 

return true; 

return false; 

/// 

/// 创建文件夹 

/// 

/// 

public void MakeDir(string dirName) 

FtpWebRequest reqFTP; 

try 

// dirName = name of the directory to create. 

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(); 

catch (Exception ex) 

Insert_Standard_ErrorLog.Insert(“FtpWeb”, “MakeDir Error –> ” + ex.Message); 

/// 

/// 获取指定文件大小 

/// 

/// 

/// 

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) 

Insert_Standard_ErrorLog.Insert(“FtpWeb”, “GetFileSize Error –> ” + ex.Message); 

return fileSize; 

/// 

/// 改名 

/// 

/// 

/// 

public void 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(); 

catch (Exception ex) 

Insert_Standard_ErrorLog.Insert(“FtpWeb”, “ReName Error –> ” + ex.Message); 

/// 

/// 移动文件 

/// 

/// 

/// 

public void MovieFile(string currentFilename, string newDirectory) 

ReName(currentFilename, newDirectory); 

}


=====================

--------------------- 

作者:Qiu_SmileToLife 

来源:CSDN 

原文:https://blog.csdn.net/m0_37467088/article/details/78133059 

版权声明:本文为博主原创文章,转载请附上博文链接!


相关文章

CopyRight:2007-2018 语言吧 备案ICP:湘ICP备09009000号-4 http://www.yuyanba.com
分享按钮