C# Serv-u連接MySQL操作文件Demo

1 Serv-U連接MySQL操作FTP文件

1-1 配置用戶

        /* Ftp服務器操作:
         * 已完成功能:上傳、下載、重命名、刪除、新建目錄、判斷目錄是都存在、獲取文件大小
         * 若出現(xiàn)bug:遠程服務器返回錯誤: (501) 參數(shù)或變量中有語法錯誤。解決方案:將目錄中的"/"修改為"http://"
         */
        /// <summary>
        /// FTP的服務器地址,格式ftp://127.0.0.1:21 進入用戶的根目錄
        /// </summary>
        private static string FtpConstr = "ftp://127.0.0.1:21";
        /// <summary>
        /// FTP服務器的用戶名
        /// </summary>
        private static string FtpUserName = "Test1";
        /// <summary>
        /// Ftp服務器的密碼
        /// </summary>
        private static string FtpPassword = "Test1";

1-2 上傳文件

將本地分文件上傳到FTP固定目錄上

        /// <summary>
        /// 上傳文件到遠程ftp 、斷點續(xù)傳 :成功
        /// </summary>
        /// <param name="path">本地的文件目錄</param>
        /// <param name="FileName">文件名稱</param>
        /// <returns></returns>
        public static bool UploadFile(string Path, string FileName)
        {
            string ErroInfo = "";
            FileInfo f = new FileInfo(Path+FileName);
            Path = Path.Replace("\\", "/");
            //傳到ftp目錄下的這個目錄下
            Path = FtpConstr + "/data/uploadFile/" + FileName;
            //根據(jù)Url創(chuàng)建FtpWebRequest對象
            FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(Path));
            reqFtp.UseBinary = true;
            //ftp用戶名和密碼
            reqFtp.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
            //在一個命令之后被執(zhí)行,默認為true(連接不會被關閉)
            reqFtp.KeepAlive = false;
            //指定執(zhí)行什么命令
            reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
            //上傳文件時通知服務器的大小
            reqFtp.ContentLength = f.Length;
            //緩沖大小為2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            //打開一個文件流:讀取上傳文件
            FileStream fs = f.OpenRead();
            try
            {
                //把上傳文件寫入流
                Stream Strm = reqFtp.GetRequestStream();
                //每次讀取文件流2kb
                contentLen = fs.Read(buff, 0, buffLength);
                //流內(nèi)容沒有結束
                while (contentLen != 0)
                {
                    //把內(nèi)容從fileStream 寫入Upload Stream
                    Strm.Write(buff, 0, buffLength);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                //關閉兩個流
                Strm.Close();
                fs.Close();
                ErroInfo = "完成";
                return true;
            }
            catch (Exception ex)
            {
                ErroInfo = string.Format("因{0},無法完成上傳", ex.Message);
                return false;
            }
        }

將本地分文件上傳到FTP目錄上

       /// <summary>
        /// 上傳文件到遠程ftp、斷點續(xù)傳 :成功
        /// </summary>
        /// <param name="ftpPath">ftp上的文件路徑</param>
        /// <param name="Path">本地的文件目錄</param>
        /// <param name="FileName">文件名</param>
        /// <returns></returns>
        public static bool UploadFile(string ftpPath, string Path, string FileName)
        {
            string ErrorInfo = "";
            FileInfo f = new FileInfo(Path+ FileName);
            Path = Path.Replace("\\", "/");
            //在Ftp上創(chuàng)建目錄
            bool b = MakeDir(ftpPath);
            if (!b)
            {
                return false;
            }
            Path = FtpConstr + ftpPath + FileName;
            FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(Path));
            reqFtp.UseBinary = true;
            reqFtp.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
            reqFtp.KeepAlive = false;
            reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
            reqFtp.ContentLength = f.Length;
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            FileStream fs = f.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();
                ErrorInfo = "完成";
                return true;
            }
            catch (Exception ex)
            {
                ErrorInfo = string.Format("因{0},無法上傳", ex.Message);
                return false;
            }
        }

1-3 下載文件

從FTP 服務器下載文件功能、斷點續(xù)傳 :成功

        /// <summary>
        /// 從FTP 服務器下載文件功能、斷點續(xù)傳 :成功
        /// </summary>
        /// <param name="FtpFilePath">FTP下載的地址</param>
        /// <param name="FilePath">存放在本地的地址</param>
        /// <param name="FileName">保存的文件名稱</param>
        /// <returns></returns>
        public static bool Download(string FtpFilePath, string FilePath, string FileName)
        {
            try
            {
                FilePath = FilePath.Replace("我的電腦\\", "");
                string onlyFileName = Path.GetFileName(FileName);
                // string newFileName = FileName + onlyFileName;
                string newFileName = FilePath + FileName;
                if (File.Exists(newFileName))
                {
                    File.Delete(newFileName);
                }
                FtpFilePath = FtpFilePath.Replace("\\", "/");
                string URL = FtpConstr + FtpFilePath;
                FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(URL));
                reqFtp.UseBinary = true;
                reqFtp.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
                //reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
                FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
                Stream StreamFtp = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = StreamFtp.Read(buffer, 0, bufferSize);
                FileStream outputStream = new FileStream(newFileName, FileMode.Create);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = StreamFtp.Read(buffer, 0, bufferSize);
                }
                StreamFtp.Close();
                outputStream.Close();
                response.Close();
                return true;

            }
            catch (Exception ex)
            {
                //ErrorInfo=string.Format("因{0},無法下載",ex.Message);
                return false;
            }
        }

1-4 FTP新建文件夾

在FTP上新建文件夾

        /// <summary>
        /// 新建文件夾:成功
        /// </summary>
        /// <param name="ftpPath">ftp文件的路徑</param>
        /// <returns></returns>
        public static bool MakeDir(string ftpPath)
        {
            string ErrorInfo = "";
            try
            {
                //判斷Ftp上的文件目錄是否存在
                bool IsExsis = RemoteFtpDirExists(ftpPath);
                if (IsExsis)
                {
                    return true;
                }
                string url = FtpConstr + ftpPath;
                FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
                reqFtp.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
                reqFtp.UseBinary = true;
                reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFtp.KeepAlive = false;
                reqFtp.GetResponse().Close();
                FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                ErrorInfo = string.Format("因{0},無法下載", ex.Message);
                return false;
            }
        }

1-5 查看FTP上是否存在某文件

查看Ftp上是否存在某文件

        /// <summary>
        /// 是否存在ftp文件:成功
        /// </summary>
        /// <param name="Path">ftp路徑</param>
        /// <returns></returns>
        public static bool RemoteFtpDirExists(string FtpPath)
        {
            bool IsExsis = false;
            FtpPath = FtpConstr + FtpPath;
            FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpPath));
            reqFtp.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
            reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
            reqFtp.KeepAlive = false;
            FtpWebResponse resFtp = null;
            try
            {
                resFtp = (FtpWebResponse)reqFtp.GetResponse();
                StreamReader stream = new StreamReader(resFtp.GetResponseStream());
                //string line = stream.ReadLine();
                //while (line != null)
                //{
                //    if (line == FileName)
                //    {
                //        IsExsis = true;
                //        break;
                //    }
                //    line = stream.ReadLine();
                //}
                IsExsis = true;
                stream.Close();
                resFtp.Close();
                return IsExsis;
            }
            catch (Exception)
            {
                if (resFtp != null)
                {
                    resFtp.Close();
                }
                return IsExsis;
            }
        }

1-6 刪除FTP文件

刪除FTP文件

        /// <summary>
        /// 刪除:成功
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool Delete(string fileName)
        {
            try
            {
                string url = FtpConstr + fileName;
                //根據(jù)Url創(chuàng)建FtpWebRequest
                FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
                reqFtp.UseBinary = true;
                //在一個命令之后被執(zhí)行,默認為true(連接不會被關閉)
                reqFtp.KeepAlive = false;
                //執(zhí)行刪除方法
                reqFtp.Method = WebRequestMethods.Ftp.DeleteFile;
                //Ftp用戶名與密碼
                reqFtp.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
                //string sStatus=listResponse.StatusDescription();
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                //ErrorInfo=string.Format("因{0},無法下載",ex.Message);
                return false;
            }
        }

1-7 獲取FTP文件大小

        /// <summary>
        /// 獲得文件大小:成功
        /// </summary>
        /// <param name="url">FTP文件的完全路徑</param>
        /// <returns></returns>
        public static long GetFileSize(string url)
        {
            long fileSize = 0;
            try
            {
                url = FtpConstr + url;
                FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
                reqFtp.UseBinary = true;
                reqFtp.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
                reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
                FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
                fileSize = response.ContentLength;

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

1-8 文件重命名

        /// <summary>
        /// 重命名 :成功
        /// </summary>
        /// <param name="ftpPath">ftp文件路徑</param>
        /// <param name="currentFilename"></param>
        /// <param name="newFilename">新文件名</param>
        public static bool FileRename(string ftpPath, string currentFileName, string newFileName)
        {
            bool success = false;
            try
            {
                string uri = FtpConstr + ftpPath + currentFileName;
                FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFtp.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
                reqFtp.UseBinary = true;
                //重命名命令
                reqFtp.Method = WebRequestMethods.Ftp.Rename;
                //重命名名字
                reqFtp.RenameTo = newFileName;

                FtpWebResponse ftpWebResponse = (FtpWebResponse)reqFtp.GetResponse();
                Stream ftpResponseStream = ftpWebResponse.GetResponseStream();
                ftpResponseStream.Close();
                ftpWebResponse.Close();
            }
            catch (Exception)
            {
                success = false;
            }
            return success;
        }

2、總結

性能:
是否安全:
數(shù)據(jù)一致性:

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • FTP服務概述 簡單FTP構建及訪問 VSFTP服務基礎 用戶禁錮、黑白名單 FTP并發(fā)及帶寬限制 一、FTP服務...
    紫_軒閱讀 8,052評論 3 25
  • 1、第八章 Samba服務器2、第八章 NFS服務器3、第十章 Linux下DNS服務器配站點,域名解析概念命令:...
    哈熝少主閱讀 3,911評論 0 10
  • 圖片更清晰,文字在最下面 FTP是TCP/IP的一種應用,使用TCP而不是UDP,所以是可靠的,面向連接的。 FT...
    停下浮躁的心閱讀 1,823評論 0 4
  • vsftpd配置文件詳解 1.默認配置: a.允許匿名用戶和本地用戶登陸。 anonymous_enable=YE...
    指間_流年閱讀 9,430評論 0 2
  • 今天和孩子討論了一下寫作文的事,很有趣。 孩子今天要寫一篇愛國英雄的故事,但是找不到合適的人物。想讓我給一點意見。...
    誠實的果果閱讀 111評論 0 1

友情鏈接更多精彩內(nèi)容