天天看點

FTP檔案上傳(自定義檔案夾)、删除、下載下傳、讀取

using System;

using System.Collections.Generic;

using System.IO;

using System.Net;

using System.Text;

namespace FTP24CP

{

    public class FtpHelper

    {

        public static string ftpServerIP = "";

        public static string ftpUserID = "";

        public static string ftpPassword = "";

        public static string saveServerDomin = "";

        /// <summary>

        /// 上傳檔案,建立檔案夾

        /// </summary>

        /// <param name="localFile"></param>

        /// <returns>檔案路徑</returns>

        public static string FtpUpload(string localFile)

        {

            DateTime dt = DateTime.Now;

            string ftpPath = "/filepath/" + dt.Year.ToString() + "/" + dt.Month.ToString() + "/" + dt.Day + "/";

            //檢查目錄是否存在,不存在建立

            FtpCheckDirectoryExist(ftpPath);

            FileInfo fi = new FileInfo(localFile);

            FileStream fs = fi.OpenRead();

            long length = fs.Length;

            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpServerIP + ftpPath + fi.Name);

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

            req.Method = WebRequestMethods.Ftp.UploadFile;

            req.ContentLength = length;

            req.Timeout = 10 * 1000;

            try

            {

                Stream stream = req.GetRequestStream();

                int BufferLength = 2048; //2K   

                byte[] b = new byte[BufferLength];

                int i;

                while ((i = fs.Read(b, 0, BufferLength)) > 0)

                {

                    stream.Write(b, 0, i);

                }

                stream.Close();

                stream.Dispose();

            }

            catch (Exception e)

            {

                string ss = e.Message + e.StackTrace;

                return "";

            }

            finally

            {

                fs.Close();

                req.Abort();

            }

            req.Abort();

            string newPath = saveServerDomin + ftpPath + fi.Name;

            return newPath;

        }

        /// <summary>

        /// 上傳檔案

        /// </summary>

        /// <param name="localFile"></param>

        /// <returns></returns>

        public static bool UploadNotCreateFile(string localFile)

        {

            FileInfo fileInf = new FileInfo(localFile);

            string uri = "" + ftpServerIP + "/" + fileInf.Name;

            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("" + ftpServerIP + "/" + fileInf.Name));

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

            reqFTP.KeepAlive = false;

            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            reqFTP.UseBinary = true;

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

                return true;

            }

            catch (Exception ex)

            {

                return false;

            }

        }

        //判斷檔案的目錄是否存,不存則建立

        public static void FtpCheckDirectoryExist(string destFilePath)

        {

            string fullDir = FtpParseDirectory(destFilePath);

            string[] dirs = fullDir.Split('/');

            string curDir = "/";

            for (int i = 0; i < dirs.Length; i++)

            {

                string dir = dirs[i];

                //如果是以/開始的路徑,第一個為空  

                if (dir != null && dir.Length > 0)

                {

                    try

                    {

                        curDir += dir + "/";

                        FtpMakeDir(curDir);

                    }

                    catch (Exception)

                    { }

                }

            }

        }

        public static string FtpParseDirectory(string destFilePath)

        {

            return destFilePath.Substring(0, destFilePath.LastIndexOf("/"));

        }

        //建立目錄

        public static bool FtpMakeDir(string localFile)

        {

            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpServerIP + localFile);

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

            req.Method = WebRequestMethods.Ftp.MakeDirectory;

            try

            {

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

                response.Close();

            }

            catch (Exception)

            {

                req.Abort();

                return false;

            }

            req.Abort();

            return true;

        }

        /// <summary>

        ///删除檔案

        /// </summary>

        /// <param name="fileName"></param>

        public static bool DeleteFTP(string fileName)

        {

            try

            {

                string uri = "" + ftpServerIP + "/" + fileName;

                FtpWebRequest reqFTP;

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("" + ftpServerIP + "/" + fileName));

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

                return true;

            }

            catch (Exception)

            {

                return false;

            }

        }

        /// <summary>

        /// ftp下載下傳檔案

        /// </summary>

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

        /// <param name="fileName"></param>

        /// <returns></returns>

        public static bool Download(string filePath, string fileName)

        {

            FtpWebRequest reqFTP;

            try

            {

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

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("" + ftpServerIP + "/" + 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();

                return true;

            }

            catch (Exception)

            {

                return false;

            }

        }

        /// <summary>

        /// 擷取檔案詳情清單

        /// </summary>

        /// <returns></returns>

        private string[] GetFilesDetailList()

        {

            string[] downloadFiles;

            try

            {

                StringBuilder result = new StringBuilder();

                FtpWebRequest ftp;

                ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("" + ftpServerIP + "/"));

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

                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;

                return downloadFiles;

            }

        }

        /// <summary>

        /// 擷取檔案清單

        /// </summary>

        /// <returns></returns>

        public string[] GetFileList()

        {

            string[] downloadFiles;

            StringBuilder result = new StringBuilder();

            FtpWebRequest reqFTP;

            try

            {

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("" + ftpServerIP + "/"));

                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)

                {

                    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;

                return downloadFiles;

            }

        }

    }

}