使用ftp上傳檔案和下載檔案—C#

來源:互聯網
上載者:User

 // ftp 檔案上傳,fileName:要上傳的檔案,fileNewname:要在伺服器上儲存的名稱
    private void Upload(string fileName, string fileNewname)
    {
        string strFileName = "";

        // 擷取檔案的相關資訊
        FileInfo fileInf = new FileInfo(fileName);
        if (fileNewname == "")
        {
            strFileName = fileInf.Name;
        }
        else
        {
            strFileName = fileNewname;
        }

        // 根據uri建立FtpWebRequest對象
        FtpWebRequest reqFTP;
        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://127.0.0.1/" + strFileName));

        // ftp使用者名稱和密碼
        reqFTP.Credentials = new NetworkCredential("yans1", "123456");

        // 銷毀到伺服器的串連
        reqFTP.KeepAlive = true;
        // 擷取或設定要發送到 FTP 伺服器的命令。
        reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
        // 傳輸檔案的資料格式Binary
        reqFTP.UseBinary = true;
        // 檔案是多大
        reqFTP.ContentLength = fileInf.Length;

        // 緩衝大小設定為2kb
        int buffLength = 2048;
        byte[] buff = new byte[buffLength];
        int contentLen;

        try
        {
            Stream strm = reqFTP.GetRequestStream();

            // 把檔案讀入到流中
            FileStream fs = fileInf.OpenRead();
            // 用於儲存要由當前請求發送到伺服器的資料。
            // 把檔案流分裝成小的位元組數組,防止佔用太多的伺服器記憶體
            contentLen = fs.Read(buff, 0, buffLength);
            // 迴圈把檔案流寫入待發給ftp伺服器的請求流中
            while (contentLen != 0)
            {
                strm.Write(buff, 0, contentLen);
                contentLen = fs.Read(buff, 0, buffLength);
            }

            fs.Close();
            strm.Close();
        }
        catch (Exception e)
        {
            Response.Write(e.Message.ToString());
        }
    }

    // ftp 檔案下載,filePath:儲存在本地的路徑,fileName:要下載的檔案名稱
    private void Download(string filePath, string fileName)
    {
        // 聲明請求
        FtpWebRequest reqFTP;
        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://127.0.0.1/"  + fileName));

        // 銷毀到伺服器的串連
        reqFTP.KeepAlive = true;
        // 設定要發送的命令形式
        reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
        // 設定要2進位傳遞檔案
        reqFTP.UseBinary = true;
        // 設定登陸的使用者名稱和密碼
        reqFTP.Credentials = new NetworkCredential("yans1",  "123456");
        //try
        //{
            // 擷取ftp給的響應
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream ftpStream = response.GetResponseStream();

            // 建立本地儲存檔案流
            FileStream outputStream = new FileStream(filePath + "/" + fileName, FileMode.Create);

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

            outputStream.Close();
            ftpStream.Close();
            response.Close();
        //}
        //catch (Exception e)
        //{
        //    Response.Write(e.Message.ToString());
        //}

    }

    // 擷取ftp的目錄下所有的檔案清單
    private string[] GetFileList()
    {
        StringBuilder result = new StringBuilder();

        // 建立請求
        FtpWebRequest reqFtp;
        reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://127.0.0.1"+"/"));

        // 佈建要求的屬性
        reqFtp.KeepAlive = true;
        reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
        reqFtp.UseBinary = true;

        // 設定使用者和密碼
        reqFtp.Credentials = new NetworkCredential("yans1", "123456");
        FtpWebResponse resFTP = (FtpWebResponse)reqFtp.GetResponse();

        // 擷取響應流
        StreamReader read = new StreamReader(resFTP.GetResponseStream());

        string line = read.ReadLine();
        while (line != null && line != "")
        {   // 判斷是檔案件,還是檔案
            result.Append(line);
            result.Append((char)1);
            line = read.ReadLine();
        }
        // 去掉最後一個 字元
        result.Remove(result.ToString().LastIndexOf((char)1), 1);
        read.Close();
        resFTP.Close();
        return result.ToString().Split((char)1);
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.