關於c#串連ftp進行上傳下載實現原理及代碼

來源:互聯網
上載者:User

複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
namespace ftponload
{
class Program
{
static void Main(string[] args)
{
//上傳檔案的方法
onload("D://outPut.txt");
//下載檔案的方法
fload();
}
public static void onload(string file)
{
//構造一個web伺服器的請求對象
FtpWebRequest ftp;
//執行個體化一個檔案對象
FileInfo f = new FileInfo(file);
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://192.168.0.150/" + f.Name));
//建立使用者名稱和密碼
ftp.Credentials = new NetworkCredential("123", "123");
ftp.KeepAlive = false;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
ftp.UseBinary = true;
ftp.ContentLength = f.Length;
int buffLength = 20480;
byte[] buff = new byte[buffLength];
int contentLen;
try
{
//獲得請求對象的輸入資料流
FileStream fs = f.OpenRead();
Stream sw = ftp.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
sw.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
sw.Close();
fs.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static void fload()
{
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://192.168.0.6/串連到你指定的檔案"));
//指定使用者名稱和密碼
ftp.Credentials = new NetworkCredential("123", "123456");
WebResponse wr = ftp.GetResponse();
StreamReader sr = new StreamReader(wr.GetResponseStream(),System.Text.Encoding.Default);
string s = sr.ReadLine();
while(s.Equals(""))
{
s = sr.ReadLine();
}
}
}
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.