tnblog
首页
视频
资源
登录

ftp 上传下载

2359人阅读 2018/12/25 19:55 总访问:26079 评论:0 收藏:0 手机
分类: FTP

ftp 上传下载:

  1. 这里的配置文件为     bin的名称.dll.config

  2. 具体如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.IO;
using System.Net;

namespace _ftp
{
    public class AgreementTools
    {
        string ftpServerIP;
        string ftpPort;
        string ftpUserID;
        string ftpPassword;
        string sUploadPath;
        string sFTPUri;
        FtpWebRequest reqFTP;
        /// <summary>
        /// 上传文件到ftp
        /// </summary>
        /// <param name="sfilepath">上传路径</param>
        /// <param name="filename">上传的文件名</param>
        ///  <param name="read">上传的文件方式</param>
        /// <returns></returns>
        public string FTP_UPFILE(string sfilepath, string filename)
        {
            string res = true;

            try
            {
                ExeConfigurationFileMap map = new ExeConfigurationFileMap();
                //读取配置文件的信息
                map.ExeConfigFilename = System.Reflection.Assembly.GetExecutingAssembly().CodeBase.Replace(@"file:///", string.Empty) + ".config";
                Configuration conf = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
                ftpServerIP = conf.AppSettings.Settings["FTPServer"].Value.ToString();
                ftpPort = conf.AppSettings.Settings["FTPPort"].Value.ToString();
                ftpUserID = conf.AppSettings.Settings["FTPUser"].Value.ToString();
                ftpPassword = conf.AppSettings.Settings["FTPPass"].Value.ToString();
                sUploadPath = conf.AppSettings.Settings["UploadPath"].Value.ToString();
                sFTPfilepath = conf.AppSettings.Settings["ftpfilepath"].Value.ToString() + filename;
            

                // 根据uri创建FtpWebRequest对象
                string sUri = "ftp://" + ftpServerIP + ":" + ftpPort + "/" + sUploadPath + "/" + sFTPfilepath;

                FileInfo fileInf = new FileInfo(sfilepath);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(sUri));

                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                // after a command is executed.
                reqFTP.KeepAlive = false;

                // Specify the command to be executed.
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

                // Specify the data transfer type.
                reqFTP.UseBinary = true;

                // Notify the server about the size of the uploaded file
                reqFTP.ContentLength = fileInf.Length;

                // The buffer size is set to 2kb
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;

                // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
                FileStream fs = fileInf.OpenRead();


                // Stream to which the file to be upload is written
                Stream strm = reqFTP.GetRequestStream();
                try
                {
                    // Read from the file stream 2kb at a time
                    contentLen = fs.Read(buff, 0, buffLength);

                    // Till Stream content ends
                    while (contentLen != 0)
                    {
                        // Write Content from the file stream to the FTP Upload Stream
                        strm.Write(buff, 0, contentLen);
                        contentLen = fs.Read(buff, 0, buffLength);
                    }

                    // Close the file stream and the Request Stream
                    strm.Close();
                    fs.Close();
                    //删除文件
                   System.IO.File.SetAttributes(sfilepath, System.IO.FileAttributes.Normal);
                   fileInf.Delete();
                }
                catch (Exception ex1)
                {
                    strm.Close();
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                res = ex.Message;
                return res;
            }

            return res;
        }
        /// <summary>
        /// 下载ftp文件
        /// </summary>
        /// <param name="sfilepath">下载文件的文件名或者相对路径;配置下文件名</param>
        /// <param name="sSavefilepath">保存文件的绝对路径</param>
        /// <returns></returns>
        public bool FTP_DOWNFILE(string sfilepath, string sSavefilepath)
        {
            bool res = true;
            try
            {
                ExeConfigurationFileMap map = new ExeConfigurationFileMap();
                //获取配置文件信息
                map.ExeConfigFilename = System.Reflection.Assembly.GetExecutingAssembly().CodeBase.Replace(@"file:///", string.Empty) + ".config";
                Configuration conf = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
                ftpServerIP = conf.AppSettings.Settings["FTPServer"].Value.ToString();
                ftpPort = conf.AppSettings.Settings["FTPPort"].Value.ToString();
                ftpUserID = conf.AppSettings.Settings["FTPUser"].Value.ToString();
                ftpPassword = conf.AppSettings.Settings["FTPPass"].Value.ToString();
                sUploadPath = conf.AppSettings.Settings["UploadPath"].Value.ToString();

                //filePath = <<The full path where the file is to be created.>>, 
                //fileName = <<Name of the file to be created(Need not be the name of the file on FTP server).>>

                string sFTPfilepath = "";
                if (read == "read")
                {
                    sFTPfilepath = conf.AppSettings.Settings["ftpfilepathread"].Value.ToString();
                }
                else
                {
                    sFTPfilepath = conf.AppSettings.Settings["ftpfilepath"].Value.ToString();
                }


                // 根据uri创建FtpWebRequest对象
                string sUri = "ftp://" + ftpServerIP + ":" + ftpPort + "/" + sUploadPath + "/" + sFTPfilepath + "/" + sfilepath;

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(sUri));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                FileStream outputStream = new FileStream(sSavefilepath, FileMode.Create);
                Stream ftpStream = response.GetResponseStream();
                try
                {
                    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 ex1)
                {
                    ftpStream.Close();
                    outputStream.Close();
                    response.Close();
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return res;
        }
    }
     
}


评价
不需要签名
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术