1. 程式人生 > >.net,C#,Ftp各種操作,上傳,下載,刪除檔案,建立目錄,刪除目錄,獲得檔案列表...

.net,C#,Ftp各種操作,上傳,下載,刪除檔案,建立目錄,刪除目錄,獲得檔案列表...

using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.IO;

using System.Windows.Forms;

namespace ConvertData

{

    class FtpUpDown

    {

        string ftpServerIP;

        string ftpUserID;

        string ftpPassword;

        FtpWebRequest reqFTP;

        private void Connect(String path)//連線ftp

        {

            // 根據uri建立FtpWebRequest物件

            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));

            // 指定資料傳輸型別

            reqFTP.UseBinary = true;

            // ftp使用者名稱和密碼

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

        }

        public FtpUpDown(string ftpServerIP, string ftpUserID, string ftpPassword)

        {

            this.ftpServerIP = ftpServerIP;

            this.ftpUserID = ftpUserID;

            this.ftpPassword = ftpPassword;

        }

        //都呼叫這個

        private string[] GetFileList(string path, string WRMethods)//上面的程式碼示例瞭如何從ftp伺服器上獲得檔案列表

        {

            string[] downloadFiles;

            StringBuilder result = new StringBuilder();

            try

            {

                Connect(path);

                reqFTP.Method = WRMethods;

                WebResponse response = reqFTP.GetResponse();

                StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文檔名

                string line = reader.ReadLine();

                while (line != null)

                {

                    result.Append(line);

                    result.Append(" ");

                    line = reader.ReadLine();

                }

                // to remove the trailing '' ''

                result.Remove(result.ToString().LastIndexOf('' ''), 1);

                reader.Close();

                response.Close();

                return result.ToString().Split('' '');

            }

            catch (Exception ex)

            {

                System.Windows.Forms.MessageBox.Show(ex.Message);

                downloadFiles = null;

                return downloadFiles;

            }

        }

        public string[] GetFileList(string path)//上面的程式碼示例瞭如何從ftp伺服器上獲得檔案列表

        {

            return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);

        }

        public string[] GetFileList()//上面的程式碼示例瞭如何從ftp伺服器上獲得檔案列表

{

            return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);

        }

        public void Upload(string filename) //上面的程式碼實現了從ftp伺服器上載檔案的功能

        {

            FileInfo fileInf = new FileInfo(filename);

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

            Connect(uri);//連線         

            // 預設為true,連線不會被關閉

            // 在一個命令之後被執行

            reqFTP.KeepAlive = false;

            // 指定執行什麼命令

            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // 上傳檔案時通知伺服器檔案的大小

            reqFTP.ContentLength = fileInf.Length;

            // 緩衝大小設定為kb

            int buffLength = 2048;

            byte[] buff = new byte[buffLength];

            int contentLen;

            // 開啟一個檔案流(System.IO.FileStream) 去讀上傳的檔案

            FileStream fs = fileInf.OpenRead();

            try

            {

                // 把上傳的檔案寫入流

                Stream strm = reqFTP.GetRequestStream();

                // 每次讀檔案流的kb

                contentLen = fs.Read(buff, 0, buffLength);

                // 流內容沒有結束

                while (contentLen != 0)

                {

                    // 把內容從file stream 寫入upload stream

                    strm.Write(buff, 0, contentLen);

                    contentLen = fs.Read(buff, 0, buffLength);

                }

                // 關閉兩個流

                strm.Close();

                fs.Close();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message, "Upload Error");

            }

        }

        public bool Download(string filePath, string fileName, out string errorinfo)/**/////上面的程式碼實現了從ftp伺服器下載檔案的功能

        {

            try

            {

                String onlyFileName = Path.GetFileName(fileName);

                string newFileName = filePath + "/" + onlyFileName;

                if (File.Exists(newFileName))

                {

                    errorinfo = string.Format("本地檔案{0}已存在,無法下載", newFileName);

                    return false;

}

                string url = "ftp://" + ftpServerIP + "/" + fileName;

                Connect(url);//連線 

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

                FileStream outputStream = new FileStream(newFileName, FileMode.Create);

                while (readCount > 0)

                {

                    outputStream.Write(buffer, 0, readCount);

                    readCount = ftpStream.Read(buffer, 0, bufferSize);

                }

                ftpStream.Close();

                outputStream.Close();

                response.Close();

                errorinfo = "";

                return true;

            }

            catch (Exception ex)

            {

                errorinfo = string.Format("因{0},無法下載", ex.Message);

                return false;

            }

        }

        //刪除檔案

        public void DeleteFileName(string fileName)

        {

            try

            {

                FileInfo fileInf = new FileInfo(fileName);

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

                Connect(uri);//連線         

                // 預設為true,連線不會被關閉

                // 在一個命令之後被執行

                reqFTP.KeepAlive = false;

                // 指定執行什麼命令

                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

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

                response.Close();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message, "刪除錯誤");

            }

}

        //建立目錄

        public void MakeDir(string dirName)

        {

            try

            {

                string uri = "ftp://" + ftpServerIP + "/" + dirName;

                Connect(uri);//連線      

                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;

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

                response.Close();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

        //刪除目錄

        public void delDir(string dirName)

        {

            try

            {

                string uri = "ftp://" + ftpServerIP + "/" + dirName;

                Connect(uri);//連線      

                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;

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

                response.Close();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

        //獲得檔案大小

        public long GetFileSize(string filename)

        {

            long fileSize = 0;

            try

            {

                FileInfo fileInf = new FileInfo(filename);

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

                Connect(uri);//連線      

                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;

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

                fileSize = response.ContentLength;

                response.Close();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

            return fileSize;

        }

        //檔案改名

        public void Rename(string currentFilename, string newFilename)

        {

            try

            {

                FileInfo fileInf = new FileInfo(currentFilename);

                string uri = "ftp://" +

ftpServerIP + "/" + fileInf.Name;

                Connect(uri);//連線

                reqFTP.Method = WebRequestMethods.Ftp.Rename;

                reqFTP.RenameTo = newFilename;

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

                //Stream ftpStream = response.GetResponseStream();

                //ftpStream.Close();

                response.Close();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

        //獲得檔案明晰

        public string[] GetFilesDetailList()

        {

            return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);

        }

        //獲得檔案明晰

        public string[] GetFilesDetailList(string path)

        {

            return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);

        }

    }

}

-----------------------

測試

       //獲得檔案列表

       private void button1_Click(object sender, EventArgs e)

        {

            FtpUpDown ftpUpDown = new FtpUpDown(ConvertData.Properties.Settings.Default.ftpServerIP, ConvertData.Properties.Settings.Default.ftpUserID, ConvertData.Properties.Settings.Default.ftpPassword);

            string[] str = ftpUpDown.GetFileList("2005");

            richTextBox1.Lines = str;

        }

        //下載

        private void button2_Click(object sender, EventArgs e)

        {

            FtpUpDown ftpUpDown = new FtpUpDown(ConvertData.Properties.Settings.Default.ftpServerIP, ConvertData.Properties.Settings.Default.ftpUserID, ConvertData.Properties.Settings.Default.ftpPassword);

            ftpUpDown.Download("c:/", "2007/11/01/57070.pdf");

        }

        //上傳

        private void button3_Click(object sender, EventArgs e)

        {

            FtpUpDown ftpUpDown = new FtpUpDown(ConvertData.Properties.Settings.Default.ftpServerIP, ConvertData.Properties.Settings.Default.ftpUserID, ConvertData.Properties.Settings.Default.ftpPassword);

            ftpUpDown.Upload("c:/57070.pdf");

        }

相關推薦

.net,C#,Ftp各種操作,,下載,刪除檔案,建立目錄,刪除目錄,獲得檔案列表...

using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; using System.Windows.Forms; namespace ConvertData {

yii2 ftp 的常規操作 下載

rec name connect dirname func username ould false tor <?php function make_directory($ftp_stream, $dir){ // if directory already

借助autoit操作下載對話框(參數化)

net htm 名稱 上傳 exe pla only cmd board 蟲師有一篇文章寫的不錯,鏈接如下:http://www.cnblogs.com/fnng/p/4188162.html 他的文章把upload.exe需要上傳的文件寫死了,下面的內容作為補充。 如

Linux使用Shell腳本實現ftp的自動下載

binary http linux user 文件中 get cal 文件重定向 tab 1. ftp自動登錄批量下載文件。#####從ftp服務器上的/home/data 到 本地的/home/databackup#####!/bin/bashftp -n<<

FTP文件下載

交互 case 所有 緩沖 沒有 如果 bye command AR ftp ftp [-v] [-n] [-i] [-d] [-g] [-s:filename] [-a] [-w:windowsize] [computer] 參數-v 禁止顯示遠程服務器響應。-n 禁

java 操作下載 HDFS:could only be replicated to 0 nodes instead of minReplication (=1). There are 1 da

環境 程式碼 //上傳檔案 public static void main(String[] args) throws Exception { Configuration configuration = new Configurati

JMeter建立FTP測試伺服器下載效能

在工作中,有時候我們會對伺服器的上傳下載效能進行測試,於是就整理了工作中測試ftp上傳下載的是實戰總結。測試環境:jmeter 我使用的是apache-jmeter-2.13測試伺服器是阿里雲上的真實伺服器,IP:***.***.***.*** (為了伺服器安全,我就不寫那麼

Android FTP 客戶端 /下載 帶進度條實戰原始碼

關於FTP我們在Android開發的時候先說一下特別需要注意,就當是正餐之前調味吧。 1.FTP是基於TCP/IP協議的常用埠是:21,也就是如果不設定埠實際上就是訪問了21埠 2.FTP程式設計要特別考慮到編碼的問題,尤其是要和FTP服務的編碼能匹配,實際上一搬都是U

配置FTP伺服器提供下載功能

本節所講內容: •      使用者和組的相關配置檔案 •      管理使用者和組 •      進入單使用者模式找回root身份 •      暴力破解rhel5下shadow檔案中的密碼 FTP服務端:xuegod63.cn   IP:192.168.1.63 FT

Mule 3.4.0中對Ftp協議的下載的應用

1.    前言 一直都聽說 Mule 對 Ftp 和 Http 協議的支援很好,於是就關注了一下。 Mule 通過一系列的配置檔案的配置就可以完成對 Ftp 伺服器的下載和上傳 ,這個還是很神奇的。 但是可惜的是, Mule 本身並不支援 FtpS 協議,只支援 SFTP ,這樣對於工業級的使用上,未免有

.net core下對於附件下載的實現

在上一篇[.net core下對於Excel的一些操作及使用]主要介紹了 .net core下excel的相關操作,本篇主要介紹下檔案的上傳與下載。 檔案上傳下載也是系統中常用的功能,不囉嗦,直接上程式碼看下具體的實現。 檔案上傳 .net c

使用Xshell遠端登入(到伺服器的)Linux系統、使用Xftp下載(伺服器)Linux系統裡面的檔案

一、遠端登入到伺服器(Xshell ) 介紹: 說明: Xshell 是目前最好的遠端登入到Linux操作的軟體,流暢的速度並且完美解決了中文亂碼的問題, 是目前程式設計師首選的軟體。 Xshell 是一個強大的安全終端模擬軟體,它支援SSH1, SSH2, 以及Micr

FTP】org.apache.commons.net.ftp.FTPClient實現復雜的下載操作目錄,處理編碼

ttr hide working log 登錄 有一個 ima spl att 和上一份簡單 上傳下載一樣 來,任何的方法不懂的,http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/

C# FTPClient--FTP操作幫助類,下載檔案目錄操作

FROM :http://www.sufeinet.com/forum.php?mod=viewthread&tid=1736&extra=page%3D1%26filter%3Dtypeid%26typeid%3D275%26typeid%3D275 這個

Webstorm/Phpstorm中設置連接FTP,並快速進行文件比較,下載,同步等操作

webstorm pwd 服務 誤操作 一份 分享 mod compare connect Phpstorm除了能直接打開localhost文件之外,還可以連接FTP,除了完成正常的數據傳遞任務之外,還可以進行本地文件與服務端文件的異同比較,同一文件自動匹配目錄上傳,下載,

java遠端操作ftp伺服器下載

 注意裡面的檔案編碼,連線過程編碼與伺服器編碼不一致的話會導致上傳中文亂碼情況。 import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.Inpu

linux shell ftp下載操作

ftp -i -v -n <<EOF open 192.168.65.1 8888 user admin 123456 cd /admin lcd D:/shell/data get "data.zip" bye EOF ftp下載,open ip port是連

JAVA 實現FTP下載(sun.net.ftp.FtpClient)

package com.why.ftp;      import java.io.DataInputStream;      import java.io.File;      import java.io.FileInputStream;      import java

使用Apache Commons Net API實現FTP下載過程中的坑點

       最近專案需要實現FTP上傳、下載功能,採用了Apache Commons Net API。程式碼很快就完成了,但由於對相關API使用場景不是很熟悉,走了一些彎路,抽一點時間做一下總結。         A)主動被動模式選擇:FTP主動模式和被動模式的詳細介紹可

C#實現FTP下載功能

//ftp的上傳功能     private void Upload(string filename)     {         FileInfo fileInf = new FileInfo(filename);         string uri = "ftp://