C# FTP上傳檔案至伺服器程式碼

weixin_34321977發表於2012-08-14
        /// <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>
        public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password)
        {
            //1. check target
            string target;
            if (targetDir.Trim() == "")
            {
                return;
            }
            target = Guid.NewGuid().ToString();  //使用臨時檔名
            

            string URI = "FTP://" + hostname + "/" + targetDir + "/" + target;
            ///WebClient webcl = new WebClient();
            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);

            //設定FTP命令 設定所要執行的FTP命令,
            //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假設此處為顯示指定路徑下的檔案列表
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //指定檔案傳輸的資料型別
            ftp.UseBinary = true;
            ftp.UsePassive = true;

            //告訴ftp檔案大小
            ftp.ContentLength = fileinfo.Length;
            //緩衝大小設定為2KB
            const int BufferSize = 2048;
            byte[] content = new byte[BufferSize - 1 + 1];
            int dataRead;

            //開啟一個檔案流 (System.IO.FileStream) 去讀上傳的檔案
            using (FileStream fs = fileinfo.OpenRead())
            {
                try
                {
                    //把上傳的檔案寫入流
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次讀檔案流的2KB
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }

                }
                catch (Exception ex) { }
                finally
                {
                    fs.Close();
                }

            }

            ftp = null;
            //設定FTP命令
            ftp = GetRequest(URI, username, password);
            ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
            ftp.RenameTo = fileinfo.Name;
            try
            {
                ftp.GetResponse();
            }
            catch (Exception ex)
            {
                ftp = GetRequest(URI, username, password);
                ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //刪除
                ftp.GetResponse();
                throw ex;
            }
            finally
            {
                //fileinfo.Delete();
            }

            // 可以記錄一個日誌  "上傳" + fileinfo.FullName + "上傳到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
            ftp = null;

            #region
            /*****
             *FtpWebResponse
             * ****/
            //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse();
            #endregion 
        }

 

 /// <summary>
        /// 下載檔案
        /// </summary>
        /// <param name="localDir">下載至本地路徑</param>
        /// <param name="FtpDir">ftp目標檔案路徑</param>
        /// <param name="FtpFile">從ftp要下載的檔名</param>
        /// <param name="hostname">ftp地址即IP</param>
        /// <param name="username">ftp使用者名稱</param>
        /// <param name="password">ftp密碼</param>
        public static void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
        {
            string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
            string tmpname = Guid.NewGuid().ToString();
            string localfile = localDir + @"\" + tmpname;

            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
            ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary = true;
            ftp.UsePassive = false;

            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    //loop to read & write to file
                    using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
                    {
                        try
                        {
                            byte[] buffer = new byte[2048];
                            int read = 0;
                            do
                            {
                                read = responseStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                            } while (!(read == 0));
                            responseStream.Close();
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception)
                        {
                            //catch error and delete file only partially downloaded
                            fs.Close();
                            //delete target file as it's incomplete
                            File.Delete(localfile);
                            throw;
                        }
                    }

                    responseStream.Close();
                }

                response.Close();
            }



            try
            {
                File.Delete(localDir + @"\" + FtpFile);
                File.Move(localfile, localDir + @"\" + FtpFile);


                ftp = null;
                ftp = GetRequest(URI, username, password);
                ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
                ftp.GetResponse();

            }
            catch (Exception ex)
            {
                File.Delete(localfile);
                throw ex;
            }

            // 記錄日誌 "從" + URI.ToString() + "下載到" + localDir + @"\" + FtpFile + "成功." );
            ftp = null;
        }

        /// <summary>
        /// 搜尋遠端檔案
        /// </summary>
        /// <param name="targetDir"></param>
        /// <param name="hostname"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="SearchPattern"></param>
        /// <returns></returns>
        public static List<string> ListDirectory(string targetDir, string hostname, string username, string password, string SearchPattern)
        {
            List<string> result = new List<string>();
            try
            {
                string URI = "FTP://" + hostname + "/" + targetDir + "/" + SearchPattern;

                System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
                ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
                ftp.UsePassive = true;
                ftp.UseBinary = true;


                string str = GetStringResponse(ftp);
                str = str.Replace("\r\n", "\r").TrimEnd('\r');
                str = str.Replace("\n", "\r");
                if (str != string.Empty)
                    result.AddRange(str.Split('\r'));

                return result;
            }
            catch { }
            return null;
        }

        private static string GetStringResponse(FtpWebRequest ftp)
        {
            //Get the result, streaming to a string
            string result = "";
            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                long size = response.ContentLength;
                using (Stream datastream = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(datastream, System.Text.Encoding.Default))
                    {
                        result = sr.ReadToEnd();
                        sr.Close();
                    }

                    datastream.Close();
                }

                response.Close();
            }

            return result;
        }

 

 

 /// 在ftp伺服器上建立目錄
        /// </summary>
        /// <param name="dirName">建立的目錄名稱</param>
        /// <param name="ftpHostIP">ftp地址</param>
        /// <param name="username">使用者名稱</param>
        /// <param name="password">密碼</param>
        public void MakeDir(string dirName,string ftpHostIP,string username,string password)
        {
            try
            {
                string uri = "ftp://" + ftpHostIP + "/" + dirName;
                System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
                ftp.Method = WebRequestMethods.Ftp.MakeDirectory;

                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

 

/// <summary>
        /// 刪除目錄
        /// </summary>
        /// <param name="dirName">建立的目錄名稱</param>
        /// <param name="ftpHostIP">ftp地址</param>
        /// <param name="username">使用者名稱</param>
        /// <param name="password">密碼</param>
        public void delDir(string dirName, string ftpHostIP, string username, string password)
        {
            try
            {
                string uri = "ftp://" + ftpHostIP + "/" + dirName;
                System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
                ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

 

/// <summary>
        /// 檔案重新命名
        /// </summary>
        /// <param name="currentFilename">當前目錄名稱</param>
        /// <param name="newFilename">重新命名目錄名稱</param>
        /// <param name="ftpServerIP">ftp地址</param>
        /// <param name="username">使用者名稱</param>
        /// <param name="password">密碼</param>
        public void Rename(string currentFilename, string newFilename, string ftpServerIP, string username, string password)
        {
            try
            {

                FileInfo fileInf = new FileInfo(currentFilename);
                string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
                System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
                ftp.Method = WebRequestMethods.Ftp.Rename;

                ftp.RenameTo = newFilename;
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();

                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

 

 private static FtpWebRequest GetRequest(string URI, string username, string password)
        {
            //根據伺服器資訊FtpWebRequest建立類的物件
            FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
            //提供身份驗證資訊
            result.Credentials = new System.Net.NetworkCredential(username, password);
            //設定請求完成之後是否保持到FTP伺服器的控制連線,預設值為true
            result.KeepAlive = false;
            return result;
        }

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

 

/// <summary>
        /// 向Ftp伺服器上傳檔案並建立和本地相同的目錄結構
        /// 遍歷目錄和子目錄的檔案
        /// </summary>
        /// <param name="file"></param>
        private void GetFileSystemInfos(FileSystemInfo file)
        {
            string getDirecName=file.Name;
            if (!ftpIsExistsFile(getDirecName, "192.168.0.172", "Anonymous", "") && file.Name.Equals(FileName))
            {
                MakeDir(getDirecName, "192.168.0.172", "Anonymous", "");
            }
            if (!file.Exists) return;
            DirectoryInfo dire = file as DirectoryInfo;
            if (dire == null) return;
            FileSystemInfo[] files = dire.GetFileSystemInfos();

            for (int i = 0; i < files.Length; i++)
            {
                FileInfo fi = files[i] as FileInfo;
                if (fi != null)
                {
                    DirectoryInfo DirecObj=fi.Directory;
                    string DireObjName = DirecObj.Name;
                    if (FileName.Equals(DireObjName))
                    {
                        UploadFile(fi, DireObjName, "192.168.0.172", "Anonymous", "");
                    }
                    else
                    {
                        Match m = Regex.Match(files[i].FullName, FileName + "+.*" + DireObjName);
                        //UploadFile(fi, FileName+"/"+DireObjName, "192.168.0.172", "Anonymous", "");
                        UploadFile(fi, m.ToString(), "192.168.0.172", "Anonymous", "");
                    }
                }
                else
                {
                    string[] ArrayStr = files[i].FullName.Split('\\');
                    string finame=files[i].Name;
                    Match m=Regex.Match(files[i].FullName,FileName+"+.*"+finame);
                    //MakeDir(ArrayStr[ArrayStr.Length - 2].ToString() + "/" + finame, "192.168.0.172", "Anonymous", "");
                    MakeDir(m.ToString(), "192.168.0.172", "Anonymous", "");
                    GetFileSystemInfos(files[i]);
                }
            }
        }

 

/// <summary>
        /// 判斷ftp伺服器上該目錄是否存在
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="ftpHostIP"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private bool ftpIsExistsFile(string dirName, string ftpHostIP, string username, string password)
        {
            bool flag = true;
            try
            {
                string uri = "ftp://" + ftpHostIP + "/" + dirName;
                System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
                ftp.Method = WebRequestMethods.Ftp.ListDirectory;

                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            }
            catch (Exception )
            {
                flag = false;
            }
            return flag;
        }

 

相關文章