ASP.NET实现FTP上传文件

ASP.NET实现FTP上传文件

ASP.NET实现的方式是:建立一个 FtpWebRequest 的实例,将IP、端口号、用户名、密码、数据、上传路径、上传文件等等复制给该实例,然后检查服务上是否有该目录,如果没有,就依次创建该目录,最后通过 FtpWebRequest 的实例的 GetRequestStream 方法远程上传文件。

其实现代码为:

  •  
  • ASP.NET 代码   复制
  • 
      using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Net;
    
    namespace FTPNS
    {
       public class FTPClass
       {
          private string Host='';//FTP主机IP
           
          private string Port='';//FTP主机端口号
           private string UserName='';//FTP主机登录用户名
           private string Userpwd='';//FTP主机登录密码
           private string UploadData='';//FTP上传数据
           private string RemoteFileName='';//FTP上传文件名       
           private string RemoteDir='';//FTP上传目录
    
            /// <summary>
           /// 创建FTP目录
            /// </summary>
           public static void MakeFTPDirectory()
           {
                FtpWebRequest req;
                FtpWebResponse response=null;
    
                req = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + Host + ":" + Port + "/" + RemoteDir));//初始化ftp目标   
                 req.Credentials = new NetworkCredential(UserName, Userpwd);
                req.Method = WebRequestMethods.Ftp.ListDirectory;
                bool bDirExists = true ;
                try
                {
                    response = req.GetResponse() as FtpWebResponse;
                }
                catch
                {
                    bDirExists = false;
                }
                finally
                {
                    if (response != null)
                        response.Close();
                }
                if (bDirExists )
                {
                   return
                }
    
                string[] dirList = RemoteDir.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                string curDir = "/";
                for (int i = 0; i < dirList.Length; i++)
                {
                    string dir = dirList[i];
                    // 如果是以/开始的路径,第一个为空  
                       if (dir != null && dir.Length > 0)
                    {
                        curDir += dir + "/";
                        req = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + Host + ":" + Port + "/" + curDir));   
                         req.Credentials = new NetworkCredential(UserName, Userpwd);
                        req.Method = WebRequestMethods.Ftp.MakeDirectory;
    
                        try
                        { 
                            response = req.GetResponse() as FtpWebResponse;
                        }
                        catch
                        {
     
                        }
                        finally
                        {
                            if(response !=null )
                                response.Close();
                        }
                    }
                }
            }
            
            public static void FTPUploadFile()
            {             
                try
                {
                    MakeFTPDirectory();
    
                    string serverPath = "ftp://" + Host + ":" + Port + "/" + RemoteDir.Replace ('\\\\','/');
                    if (!serverPath.EndsWith("/"))
                        serverPath += "/";
    
                    serverPath += RemoteFileName;
    
                    FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverPath ));   
                    req.Method = WebRequestMethods.Ftp.UploadFile;  
                    req.UseBinary =true;
                    req.Credentials = new NetworkCredential(UserName, Userpwd);// 登录凭证   
                     req.ContentLength = UploadData.Length;
                    int bufferSize = 4096;
                    int length;
                    byte[] buffer = new byte[bufferSize];
                    int seek = 0;
                    // 将文件流存在FileStream中   
                      using (MemoryStream fs = new MemoryStream(UploadData))
                    {
                        // 上传流指向Stream   
                        using (Stream stream = req.GetRequestStream())
                        {
                            // 读取文件流中最大长度为bufferSize字节内容至buffer,读取长度返回至length   
                            length = fs.Read(buffer, 0, bufferSize);
                            // 如果读取到了内容   
                                 while (length != 0)
                            {
                                //buffer写入上传流   
                                     stream.Write(buffer, 0, length);
                                     seek += length;
                                //继续读取   
                                     length = fs.Read(buffer, 0, bufferSize);
                            }
                        }
                    }
                    FtpWebResponse response = req.GetResponse() as FtpWebResponse;
                    response.Close();
                }
                catch (Exception e)
                {
                   
                }
            }    
        }
    }