【.NET】FTP服务器上传下载

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        public static string strFileContent = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            //GetFilesDetailList();
            string strPath = "FTP://192.168.1.24/1.png";//FTP服务器文件地址
            string strFileName = "1.png";
            //拼接超链接  
            strFileContent = "<a class=\"ke-insertfile\" href=\"/DownLoad.aspx?strPath=" + strPath + "&strFileName=" + strFileName + "\" target=\"_blank\">" + strFileName + "</a>"; 
        }
        //上传
        protected void btnUpLoad_Click(object sender, EventArgs e)
        {
            string strFtpPath = "FTP://192.168.1.24";   //ftp地址  
            string strUserName = "WNC";    //用户名  
            string strPassword = "258";  //密码    
            Boolean flag = false;

            string strFullName = "";
            if (fuImage.PostedFile.FileName != "")
            {
                strFullName = fuImage.PostedFile.FileName;  //所选择文件的路径  
            }
            else
            {
                Response.Write("<script>alert('请选择要上传的文件!');</script>");
            }

            //上传文件  
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(fuImage.PostedFile.FileName);
            flag = UploadFile(fileInfo, strFtpPath, strUserName, strPassword);

            if (flag == true)
            {
                Response.Write("<script>alert('文件上传成功!');</script>");
            }
            else
            {
                Response.Write("<script>alert('文件上传失败!');</script>");
            }
        }

        /// <summary>  
        /// 上传文件  
        /// </summary>  
        /// <param name="fileinfo">需要上传的文件</param>  
        /// <param name="targetDir">目标路径</param>  
        /// <param name="hostname">ftp地址</param>  
        /// <param name="username">ftp用户名</param>  
        /// <param name="password">ftp密码</param>  
        /// <returns></returns>  
        public static Boolean UploadFile(System.IO.FileInfo fileinfo, string hostname, string username, string password)
        {
            string strExtension = System.IO.Path.GetExtension(fileinfo.FullName);
            string strFileName = "";

            strFileName = fileinfo.Name;    //获取文件的文件名  
            string URI = hostname + "/" + strFileName; //上传服务器的根目录下

            //获取ftp对象  
            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);

            //设置ftp方法为上传  
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

            //制定文件传输的数据类型  
            ftp.UseBinary = true;
            ftp.UsePassive = true;


            //文件大小  
            ftp.ContentLength = fileinfo.Length;
            //缓冲大小设置为20kb  
            const int BufferSize = 20480;

            byte[] content = new byte[BufferSize - 1 + 1];
            int dataRead;

            //打开一个文件流(System.IO.FileStream)去读上传的文件  
            using (System.IO.FileStream fs = fileinfo.OpenRead())
            {
                try
                {
                    //把上传的文件写入流  
                    using (System.IO.Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次读文件流的2KB  
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    ftp = null;
                    ftp = GetRequest(URI, username, password);
                    ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;//删除  
                    ftp.GetResponse();
                    return false;
                }
                finally
                {
                    fs.Close();
                }
            }



        }

        /// <summary>  
        /// 得到ftp对象  
        /// </summary>  
        /// <param name="URI">ftp地址</param>  
        /// <param name="username">ftp用户名</param>  
        /// <param name="password">ftp密码</param>  
        /// <returns>返回ftp对象</returns>  
        private static System.Net.FtpWebRequest GetRequest(string URI, string username, string password)
        {
            //根据服务器信息FtpWebRequest创建类的对象  
            FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
            //提供身份验证信息  
            result.Credentials = new System.Net.NetworkCredential(username, password);
            //result.Credentials = new System.Net.NetworkCredential();  
            //设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true  
            result.KeepAlive = false;
            return result;
        }

        //重命名文件
        protected void btnReName_Click(object sender, EventArgs e)
        {
            string strPath = "ftp://192.168.1.24/1.png";    //文件在ftp服务器中存放路径  
            string strUserName = "WNC";    //登录用户名  
            string strPassword = "258";  //登录密码  
            string strNewFileName = "xixi.png"; //新文件名  

            //获取ftp对象  
            System.Net.FtpWebRequest ftp = GetRequest(strPath, strUserName, strPassword);
            //设置ftp命令  
            ftp.Method = System.Net.WebRequestMethods.Ftp.Rename;//改名  
            ftp.RenameTo = strNewFileName;
            ftp.GetResponse(); 
        }
        //删除文件
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string strPath = "ftp://192.168.1.24/xixi.png";    //文件在ftp服务器中存放路径  
            string strUserName = "WNC";    //登录用户名  
            string strPassword = "258";  //登录密码  

            //获取ftp对象  
            System.Net.FtpWebRequest ftp = GetRequest(strPath, strUserName, strPassword);
            //设置ftp命令  
            ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;//删除  
            ftp.GetResponse(); 
        }

        /// 获取当前目录下明细(包含文件和文件夹)
        /// </summary>
        /// <returns></returns>
        public string[] GetFilesDetailList()
        {
            string strPath = "ftp://192.168.1.24";
            string ftpUserID = "WNC";
            string ftpPassword = "258";
            string[] downloadFiles;
            try
            {
                StringBuilder result = new StringBuilder();
                FtpWebRequest ftp;
                ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(strPath));
                ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string line = reader.ReadLine();
                while (line != null){
                    
                    result.Append(line);
                    strFileContent = "<a class=\"ke-insertfile\" href=\"/DownLoad.aspx?strPath=" + strPath
                        + "&strFileName=" + line + "\" target=\"_blank\">" + line + "</a>"; 
                    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;
                return downloadFiles;
            }
        }

    }
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="page_upload.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
     <form id="form1" runat="server">  
    <div>  
    <asp:FileUpload ID="fuImage" runat="server" Width="400px" />  
    <asp:Button runat="server" ID="btnUpLoad" Text="上传" CssClass="nButton" OnClick="btnUpLoad_Click" />  
    </div> 
    <div>
         <%= strFileContent %>   <%--需要下载的文件名--%> 
    </div> 
    <div>  
        <asp:Button runat="server" ID="btnReName" Text="重命名" CssClass="nButton" OnClick="btnReName_Click" /> 
        <asp:Button runat="server" ID="btnDelete" Text="删除" CssClass="nButton" OnClick="btnDelete_Click" />   
    </div>    
    </form> 
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            UpDownLoad();
        }

        /// <summary>  
        /// 下载附件  
        /// </summary>  
        public void UpDownLoad()
        {

            string strPath = Request["strPath"].ToString(); //该文件在ftp服务器中的存放路径  
            string strFileName = Request["strFileName"].ToString(); //文件名  
            string strUserName = "WNC";    //ftp登录用户名  
            string strPassword = "258";  //ftp登录密码  

            System.Net.WebClient request = new System.Net.WebClient();
            request.Credentials = new System.Net.NetworkCredential(strUserName, strPassword);//认证FTP用户名密码    
            byte[] newFileData = request.DownloadData(strPath);

            //下载文件  
            DownLoadFile(strFileName, newFileData, this.Page);


        }

        public static void DownLoadFile(string FileName, byte[] Context, Page page)
        {
            page.Response.ContentType = "application/octet-stream";
            if (FileName == "")
            {
                FileName = "Temp";
            }
            FileName = ToHexString(FileName);
            page.Response.AddHeader("Content-Disposition", "attachment;FileName=" + FileName);
            if (Context != null && Context.Length > 0)
                page.Response.OutputStream.Write(Context, 0, Context.Length);
            else
                page.Response.BinaryWrite(new byte[1]);
            page.Response.End();
        }


        public static string ToHexString(string s)
        {
            char[] chars = s.ToCharArray();
            StringBuilder builder = new StringBuilder();
            for (int index = 0; index < chars.Length; index++)
            {
                bool needToEncode = NeedToEncode(chars[index]);
                if (needToEncode)
                {
                    string encodedString = ToHexString(chars[index]);
                    builder.Append(encodedString);
                }
                else
                {
                    builder.Append(chars[index]);
                }
            }

            return builder.ToString();
        }

        private static bool NeedToEncode(char chr)
        {
            string reservedChars = "$-_.+!*'(),@=&";

            if (chr > 127)
                return true;
            if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
                return false;

            return true;
        }

        private static string ToHexString(char chr)
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            byte[] encodedBytes = utf8.GetBytes(chr.ToString());
            StringBuilder builder = new StringBuilder();
            for (int index = 0; index < encodedBytes.Length; index++)
            {
                builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
            }
            return builder.ToString();
        }  
    }
}

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DownLoad.aspx.cs" Inherits="WebApplication1.WebForm2" %>

<!DOCTYPE html>
<%--<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
    <title></title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  </div>  
    </form>  
</body>  
</html>--%> 


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值