FTP文件上传、下载、获取文件列表、文件夹列表

	/// <summary>
    /// 判断FTP文件是否存在
    internal static bool DirectoryExist(FTPparama parama)
    {
        var ftppath = parama.FTPPath;
        if (parama.LX == 1)
        {
            ftppath = parama.FTPPath + "/" + parama.TXM;
        }
        FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftppath));
        reqFtp.UseBinary = true;
        reqFtp.Credentials = new NetworkCredential(parama.username, parama.password);
        reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
        FtpWebResponse resFtp = null;
        try
        {
            resFtp = (FtpWebResponse)reqFtp.GetResponse();
            FtpStatusCode code = resFtp.StatusCode;//OpeningData
            resFtp.Close();
            return true;
        }
        catch
        {
            if (resFtp != null)
            {
                resFtp.Close();
            }
            return false;
        }
    }
    /// <summary>
    /// 创建目录
    /// </summary>
    /// <param name="dirName"></param>
    internal static void MakeDir(FTPparama parama)
    {
        try
        {
            string uri = parama.FTPPath + "/" + parama.TXM;

            //string uri = "ftp://" + ftpServerIP + "/" + dirName;
            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            reqFTP.Credentials = new NetworkCredential(parama.username, parama.password);
            //Connect(uri);//连接       
            reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
            reqFTP.KeepAlive = false;
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            response.Close();
        }

        catch (Exception ex)
        {
            throw new Exception("创建文件失败,原因: " + ex.Message);
        }

    }

    // 上传文件到远程ftp
    internal static bool UploadFile(FTPparama parama)
    {
        string ftppath = parama.FTPPath + "/" + parama.TXM;
        string pathfile = parama.path + @"\" + parama.filname;
        string erroinfo = "";
        string path;
        FileInfo f = new FileInfo(pathfile);
        path = parama.path.Replace("\\", "/");
        //bool b = MakeDir(ftpPath);
        //if (b == false)
        //{
        //    return false;
        //}
        path = ftppath + "/" + parama.filname;
        FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
        reqFtp.UseBinary = true;
        reqFtp.Credentials = new NetworkCredential(parama.username, parama.password);
        reqFtp.KeepAlive = false;
        reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
        reqFtp.ContentLength = f.Length;
        int buffLength = 2048;
        byte[] buff = new byte[buffLength];
        int contentLen;
        FileStream fs = f.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();
            erroinfo = "完成";
            return true;
        }
        catch (Exception ex)
        {
            erroinfo = string.Format("因{0},无法完成上传", ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 从ftp服务器上获得文件列表
    /// </summary>
    /// <returns></returns>
    internal static List<string> GetFile(FTPparama parama)
    {
        List<string> strs = new List<string>();
        try
        {
            string uri = parama.FTPPath + "/" + parama.TXM;   //目标路径 path为服务器地址
            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            // ftp用户名和密码
            reqFTP.Credentials = new NetworkCredential(parama.username, parama.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("<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;
    }

    /// <summary>
    /// 从ftp服务器删除文件的功能
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    internal static bool DeleteFile(FTPparama parama)
    {
        try
        {
            string url = parama.path + parama.filname;
            FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
            reqFtp.UseBinary = true;
            reqFtp.KeepAlive = false;
            reqFtp.Method = WebRequestMethods.Ftp.DeleteFile;
            reqFtp.Credentials = new NetworkCredential(parama.username, parama.password);
            FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
            response.Close();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    /// <summary>
    /// 从ftp服务器下载文件的功能
    /// </summary>
    /// <param name="ftpfilepath">ftp下载的地址</param>
    /// <param name="filePath">存放到本地的路径</param>
    /// <param name="fileName">保存的文件名称</param>
    /// <returns></returns>
    internal static bool Download(FTPparama parama)
    {
        string paths = "";
        try
        {
            paths = parama.path.Replace("\\", "/");
            String onlyFileName = Path.GetFileName(parama.filname);
            string newFileName = parama.path + @"/" + onlyFileName;
            if (File.Exists(newFileName))
            {
                File.Delete(newFileName);
            }
            parama.FTPPath = parama.FTPPath.Replace("\\", "/");
            string url = parama.FTPPath + "/" + parama.TXM + "/" + parama.filname; ;
            FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
            reqFtp.UseBinary = true;
            reqFtp.Credentials = new NetworkCredential(parama.username, parama.password);
            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);
            FileStream outputStream = new FileStream(newFileName, FileMode.Create);
            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)
        {
            //errorinfo = string.Format("因{0},无法下载", ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 从ftp服务器上获得文件夹列表
    /// </summary>
    /// <param name="RequedstPath">服务器下的相对路径</param>
    /// <returns></returns>
    internal static List<string> GetDirctory(FTPparama parama)
    {
        List<string> strs = new List<string>();
        try
        {
            string uri = parama.FTPPath;   //目标路径 path为服务器地址
            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            // ftp用户名和密码
            reqFTP.Credentials = new NetworkCredential(parama.username, parama.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("<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;
    }
}

class FTPparama
{
    public string FTPPath { get; set; }//ftp服务器地址
    public string path { get; set; }//本地路径
    public string username { get; set; }//ftp文件访问的用户名
    public string password { get; set; }//ftp文件访问的密码
    public string filname { get; set; }//文件名
    public string TXM { get; set; }//条形码
    public int LX { get; set; }//判断是什么时候检验文件夹是否存在的,等于1的时候路径加了条形码
}

[更多使用,参考](https://www.cnblogs.com/zhenzaizai/p/7434669.html)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MFC FTP文件夹的步骤如下: 1. 打开文件夹获取其中的所有文件和子文件夹。 2. 连接FTP服务器,并在服务器上创建一个与本地文件夹同名的文件夹。 3. 递归上文件夹中的每个文件和子文件夹。 4. 对于每个文件,使用FTP命令将其上到服务器上的文件夹中。 5. 对于每个子文件夹,使用FTP命令在服务器上创建一个与本地子文件夹同名的文件夹,并递归上该子文件夹。 以下是一些示例代码,可以用作参考: ```c++ void CFtpClient::UploadFolder(CString strLocalFolder, CString strRemoteFolder) { CFileFind finder; CString strWildcard = strLocalFolder + _T("\\*.*"); BOOL bWorking = finder.FindFile(strWildcard); while (bWorking) { bWorking = finder.FindNextFile(); if (finder.IsDots()) continue; CString strFileName = finder.GetFileName(); CString strFilePath = finder.GetFilePath(); if (finder.IsDirectory()) { CString strNewRemoteFolder = strRemoteFolder + _T("/") + strFileName; CreateRemoteFolder(strNewRemoteFolder); // 在FTP服务器上创建子文件夹 UploadFolder(strFilePath, strNewRemoteFolder); // 递归上文件夹 } else { CString strRemoteFilePath = strRemoteFolder + _T("/") + strFileName; UploadFile(strFilePath, strRemoteFilePath); // 上文件FTP服务器上的文件夹 } } } void CFtpClient::CreateRemoteFolder(CString strRemoteFolder) { m_ftpConnection.CreateDirectory(strRemoteFolder); } void CFtpClient::UploadFile(CString strLocalFilePath, CString strRemoteFilePath) { m_ftpConnection.PutFile(strLocalFilePath, strRemoteFilePath); } ``` 其中,CFtpClient是一个MFC封装的FTP客户端类,包含了连接FTP服务器、上文件等操作的实现。UploadFolder方法接受本地文件夹路径和服务器文件夹路径作为参数,用于递归上整个文件夹。CreateRemoteFolder方法用于在FTP服务器上创建文件夹,UploadFile方法用于上单个文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值