Đăng nhập | Đăng ký
Đăng nhập , với với

Diễn đàn    ASP.NET & Sharepoint MOSS, WSS 2007    Thư viện FTPClient chuẩn  

Thành viênNội dung
aspnet

Lập trình không biên giới
446  bài
10-11-2009 02:54:36

public class FTPClient
{
private string remoteHost;
private string remoteUser;
private string remotePass;
private string remotePath;

private int remotePort = 21;
private int bytes;
private Socket clientSocket;

private int retValue;
private Boolean logined;
private string reply;
private string mes = "";

private static int BLOCK_SIZE = 512;

Byte[] buffer = new Byte[BLOCK_SIZE];
Encoding ASCII = Encoding.ASCII;

public FTPClient(string host, string user, string password)
{
remoteHost = host;
remoteUser = user;
remotePass = password;
Login();
}

public void Login()
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(Dns.Resolve(remoteHost).AddressList[0], remotePort);

try
{
clientSocket.Connect(ep);
}
catch (Exception)
{
throw new IOException("Couldn't connect to remote server");
}

ReadReply();
if (retValue != 220)
{
Close();
throw new IOException(reply.Substring(4));
}

SendCommand("USER " + remoteUser);
if (!(retValue == 331 || retValue == 230))
{
CleanUp();
throw new IOException(reply.Substring(4));
}

if (retValue != 230)
{
SendCommand("PASS " + remotePass);
if (!(retValue == 230 || retValue == 202))
{
CleanUp();
throw new IOException(reply.Substring(4));
}
}

logined = true;
}

private void ChangeDir(string dirName)
{
if (dirName.Equals("."))
{
return;
}

SendCommand("CWD " + dirName);

if (retValue != 250)
{
throw new IOException(reply.Substring(4));
}

this.remotePath = dirName;
}

private void ReadReply()
{
mes = "";
reply = ReadLine();
retValue = Int32.Parse(reply.Substring(0, 3));
}

private string ReadLine()
{
while (true)
{
bytes = clientSocket.Receive(buffer, buffer.Length, 0);
mes += ASCII.GetString(buffer, 0, bytes);
if (bytes < buffer.Length)
{
break;
}
}

string[] messages = mes.Split('\n');

if (mes.Length > 2)
{
mes = messages[messages.Length - 2];
}
else
{
mes = messages[0];
}

if (!mes.Substring(3, 1).Equals(" "))
{
return ReadLine();
}

return mes;
}

private void SendCommand(string command)
{
Byte[] cmdBytes = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray());
clientSocket.Send(cmdBytes, cmdBytes.Length, 0);
ReadReply();
}

public void Close()
{
if (clientSocket != null)
{
SendCommand("QUIT");
}

CleanUp();
}

public void CleanUp()
{
if (clientSocket != null)
{
clientSocket.Close();
clientSocket = null;
}
logined = false;
}

public void UploadFile(string fileName, Stream filePosted)
{
Socket cSocket = CreateDataSocket();
//long offset = 0;

//if (resume)
//{
// try
// {
// SetBinaryMode(true);
// offset = getFileSize(fileName);
// }
// catch (Exception)
// {
// offset = 0;
// }
//}

//if (offset > 0)
//{
// SendCommand("REST " + offset);
// if (retValue != 350)
// {
// offset = 0;
// }
//}

SendCommand("STOR " + fileName);

if (!(retValue == 125 || retValue == 150))
{
throw new IOException(reply.Substring(4));
}

while ((bytes = filePosted.Read(buffer, 0, buffer.Length)) > 0)
{
cSocket.Send(buffer, bytes, 0);
}

filePosted.Close();
if (cSocket.Connected)
{
cSocket.Close();
}

ReadReply();
if (!(retValue == 226 || retValue == 250))
{
throw new IOException(reply.Substring(4));
}
}

private Socket CreateDataSocket()
{
SendCommand("PASV");

if (retValue != 227)
{
throw new IOException(reply.Substring(4));
}

int index1 = reply.IndexOf('(');
int index2 = reply.IndexOf(')');
string ipData = reply.Substring(index1 + 1, index2 - index1 - 1);
int[] parts = new int[6];

int len = ipData.Length;
int partCount = 0;
string buf = "";

for (int i = 0; i < len && partCount <= 6; i++)
{

char ch = Char.Parse(ipData.Substring(i, 1));
if (Char.IsDigit(ch))
buf += ch;
else if (ch != ',')
{
throw new IOException("Malformed PASV reply: " + reply);
}

if (ch == ',' || i + 1 == len)
{

try
{
parts[partCount++] = Int32.Parse(buf);
buf = "";
}
catch (Exception)
{
throw new IOException("Malformed PASV reply: " + reply);
}
}
}

string ipAddress = parts[0] + "." + parts[1] + "." +
parts[2] + "." + parts[3];

int port = (parts[4] << 8) + parts[5];

Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(Dns.Resolve(ipAddress).AddressList[0], port);

try
{
s.Connect(ep);
}
catch (Exception)
{
throw new IOException("Can't connect to remote server");
}

return s;
}

private void SetBinaryMode(bool mode)
{
if (mode)
{
SendCommand("TYPE I");
}
else
{
SendCommand("TYPE A");
}

if (retValue != 200)
{
throw new IOException(reply.Substring(4));
}
}
}


Chia sẻ với bà con, cái này được viết trên java, có 1 chú rất chăm chỉ chuyển sang dotnet, chạy ổn định gần như không có lỗi
 

Chủ đề gần đây :

Cùng loại :

 
Tên file Người đăng Ngày Lượt
News Ticker Demo.rar
jQuery Carousellite cho cuộn các khối tin nhẹ nhàng mượt mà, sử dụng cho module Tin tức (CMS) hoặc giới thiệu sản phẩm
aspnet 5/7/2011 8:59:52 AM 663
cms_source_dll_sql_2010.rar
source C# + SQL Script + Dll module CMS trên DNN 5x, (bản chạy ổn định không lỗi)
aspnet 9/5/2010 6:05:54 PM 2154
killforever.rar
Script diệt virus forever.exe (lây nhiễm qua USB) mà không cần cài lại window
aspnet 7/28/2010 6:51:30 AM 304
CSharp Coding Standards.pdf
C# Coding standard, for all user, quy tắc viết mã lập trình c# dotnet.
aspnet 6/1/2010 8:27:39 AM 1371
weather_forex_gold.rar
module DNN : "vàng + thời tiết + tỷ giá ngoại tệ" của seekill
coder 3/11/2010 3:50:09 AM 1241
Training DotNetNuke.zip
Tài liệu hướng dẫn cài đặt DNN, tạo module DNN đơn giản, nâng cao
quanlv 9/30/2009 9:11:36 AM 3262
Viet va them 1 module don gian vao website.doc
Hướng dẫn viết module đơn giản trên DNN (word) có hình, gửi bởi vinahana
aspnet 9/18/2009 6:15:24 PM 1564
Moduel NEWs Demo.zip
Một số module bao gồm: News, WorkScheduler, QA, Comment, Menu, ...
quanlv 8/22/2009 10:44:15 AM 2932
MenuDNN5.rar
Menu DNN 51 Page.aspx
aspnet 7/21/2009 12:22:38 PM 2039
diendan.zip
Cài đặt diễn đàn (VSP) chỉ với 4 bước.
aspnet 6/15/2009 2:18:13 AM 1516
roll_updown.zip
Roll up, roll down news list using javascript, simple, easy to use.
radiogaga 6/1/2009 11:29:51 AM 456
rotator-1.0.0.rar
Auto Scroll News - tự động cuộn tin tức bằng JS
dotnetvn 5/30/2009 3:21:22 PM 682
captcha2.rar
CAPTCHA sinh ngẫu nhiên : size, font, position, color ... vẽ line gây nhiễu chống reCAPTCHA bot.
tieuphu 5/30/2009 2:34:42 PM 669
MenuDNN.zip
Menu Dọc cho DNN (Tác giả Võ Thế Quang)
biennv 5/27/2009 8:07:47 AM 1551
Gioi_thieu_san_pham_unisched4.zip
Giới thiệu phần mềm xếp thời khóa biểu đại học (University Scheduling 4.0) : áp dụng cho mô hình xếp thời khóa biểu niên chế, tại các trường đại học và cao đẳng tại việt nam
khanhjin 5/12/2009 5:00:02 PM 3418
HitCounterInDatabaseASPNET.zip
HitCounter
nguyentx 4/20/2009 4:38:04 PM 601
s3Slide.rar
Slide show chuyên nghiệp, giống tintuconline.com.vn
coder 4/9/2009 9:34:41 AM 2470
XMLPROG.zip
XML Programing C# dotnet
aspnet 4/4/2009 10:02:43 AM 652
menu_vnexpress.rar
Tạo menu giống vnexpress = xsl transform, C# dotnet, javascript(Toàn bộ mã nguồn).
coder 3/30/2009 10:14:50 PM 2628
DesktopModules.rar
CMS dotnetnuke + Image Library + Core CMS (DNN Data Provider) version 1.1
aspnet 3/30/2009 5:23:14 PM 2224
CODERVN.NET
Công ty cổ phần công nghệ và dịch vụ AWAS
Công ty cổ phần công nghệ và dịch vụ AWAS, cổng thông tin, chính phủ điện tử, phần mềm quản lý điểm, quản lý sinh viên, http://awas.vn, http://awas.com.vn, phần mềm ứng dụng, dịch vụ công trực tuyến, thiết kế website, thiet ke web, thiết kế web, điện lực, phần mềm quản lý đào tạo, cao đẳng, đại học,cổng thông tin tích hợp, cổng thông tin điện tử, webportal, thư viện điện tử, electric library, library online, email, web, quản lý quan hệ khách hàng, CRM, dịch vụ công trực tuyến, phần mềm hành chính một cửa,