C # Version of FTP method implementation class Code _c# tutorial
Last Update:2017-01-18
Source: Internet
Author: User
/*
FTPFactory.cs
Better View with Tab space=4
Written by Jaimon Mathew (Jaimonmathew@rediffmail.com)
Rolander,dan (Dan.Rolander@marriott.com) has modified the
Download
method to cope with the file name with path information. He also
Provided
The XML comments so the library provides Intellisense
Descriptions.
Use the following line to compile
Csc/target:library/out:ftplib.dll/r:system.dll FTPFactory.cs
*/
Using System;
Using System.Threading;
Using System.Net;
Using System.IO;
Using System.Text;
Using System.Net.Sockets;
Using System.Configuration;
Namespace Audiocollect
{
<summary>
Summary description of the ftpfactory.
</summary>
public class Ftpfactory
{
Static readonly log4net. ILog log = log4net. Logmanager.getlogger ("log4net");
private string
Remotehost,remotepath,remoteuser,remotepass,mes;
private int remoteport,bytes;
Private Socket Clientsocket;
private int retvalue;
Private Boolean Debug;
Private Boolean logined;
private string reply;
private static int block_size = 512;
byte[] buffer = new Byte[block_size];
Encoding ASCII = encoding.ascii;
Public Ftpfactory ()
{
String ftpremoteip = configurationsettings.appsettings["Ftpremoteip"];
int ftpremoteport = Convert.ToInt32 (configurationsettings.appsettings["Ftpremoteport"]);
String ftpuser = configurationsettings.appsettings["Ftpuser"];
String FTPPassword = configurationsettings.appsettings["FTPPassword"];
RemoteHost = Ftpremoteip;
RemotePath = ".";
RemoteUser = Ftpuser;
Remotepass = FTPPassword;
RemotePort =ftpremoteport;
debug = false;
logined = false;
}
///
Set the name of the FTP server to connect to.
///
Server Name
public void Setremotehost (string remotehost)
{
This.remotehost = RemoteHost;
}
///
Return the name of the current FTP server.
///
Server Name
public string Getremotehost ()
{
return remotehost;
}
///
Set the port number to use for FTP.
///
Port number
public void Setremoteport (int remoteport)
{
This.remoteport = RemotePort;
}
///
Return the current port number.
///
Current port number
public int Getremoteport ()
{
return remoteport;
}
///
Set the remote directory path.
///
The Remote directory path
public void Setremotepath (string remotepath)
{
This.remotepath = RemotePath;
}
///
Return to the current remote directory path.
///
The current remote directory path.
public string Getremotepath ()
{
return remotepath;
}
///
Set the user name to a logging into the remote server.
///
Username
public void Setremoteuser (string remoteuser)
{
This.remoteuser = RemoteUser;
}
///
Set the password to user for logging into the remote server.
///
Password
public void Setremotepass (string remotepass)
{
This.remotepass = Remotepass;
}
///
Return a string array containing the remote directory file list.
///
///
///
Public string[] Getfilelist (String mask)
{
if (!logined)
{
Login ();
}
Socket cSocket = Createdatasocket ();
SendCommand ("NLST" + mask);
if (!) ( RetValue = 150 | | RetValue = 125))
{
throw new IOException (reply. Substring (4));
}
Mes = "";
Thread.Sleep (700);
while (true)
{
if (csocket.connected)
{
int bytes = csocket.receive (buffer, buffer. Length, 0);
Mes + + ASCII. GetString (buffer, 0, bytes);
if (bytes < buffer. Length)
{
Break
}
}
Else
{
Log. Info (The socket connection is broken!) ");
}
}
Log. Info (MES);
Char[] seperator = {' \ n '};
String[] mess = mes. Split (Seperator);
foreach (String fileName in Mess)
{
Log. Info (FileName);
}
Csocket.close ();
Readreply ();
if (RetValue!= 226)
{
throw new IOException (reply. Substring (4));
}
return mess;
}
Public string[] Getfilelist ()
{
if (!logined)
{
Login ();
}
Socket cSocket = Createdatasocket ();
SendCommand ("LIST");
if (!) ( RetValue = 150 | | RetValue = 125))
{
throw new IOException (reply. Substring (4));
}
Mes = "";
while (true)
{
int bytes = csocket.receive (buffer, buffer. Length, 0);
Mes + + ASCII. GetString (buffer, 0, bytes);
if (bytes < buffer. Length)
{
Break
}
}
Log. Info (MES);
Char[] seperator = {' \ n '};
String[] mess = mes. Split (Seperator);
Csocket.close ();
Readreply ();
if (RetValue!= 226)
{
throw new IOException (reply. Substring (4));
}
return mess;
}
///
Return the size of a file.
///
///
///
Public long GetFileSize (string fileName)
{
if (!logined)
{
Login ();
}
SendCommand ("SIZE" + fileName);
Long size=0;
if (RetValue = 213)
{
Size = Int64.parse (reply. Substring (4));
}
Else
{
throw new IOException (reply. Substring (4));
}
return size;
}
///
Login to the remote server.
///
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));
}
if (Debug)
Console.WriteLine ("USER" +remoteuser);
SendCommand ("USER" +remoteuser);
if (!) ( RetValue = 331 | | RetValue = 230))
{
Cleanup ();
throw new IOException (reply. Substring (4));
}
if (RetValue!= 230)
{
if (Debug)
Console.WriteLine ("Pass xxx");
SendCommand ("pass" +remotepass);
if (!) ( RetValue = 230 | | RetValue = 202))
{
Cleanup ();
throw new IOException (reply. Substring (4));
}
}
Logined = true;
Console.WriteLine ("Connected to" +remotehost);
ChDir (RemotePath);
}
///
If the value of mode is true, set binary mode for downloads.
Else, set Ascii mode.
///
///
public void Setbinarymode (Boolean mode)
{
if (mode)
{
SendCommand ("TYPE I");
}
Else
{
SendCommand ("TYPE A");
}
if (RetValue!= 200)
{
throw new IOException (reply. Substring (4));
}
}
///
Download a file to the Assembly ' s local directory,
Keeping the same file name.
///
///
public void Download (string remfilename)
{
Download (Remfilename, "", false);
}
///
Download a remote file to the Assembly ' s local directory,
Keeping the same file name, and set the resume flag.
///
///
///
public void Download (string Remfilename,boolean resume)
{
Download (Remfilename, "", resume);
}
///
Download a remote file to a local file name which can include
A path. The local file name would be created or overwritten,
But the path must exist.
///
///
///
public void Download (string remfilename,string locfilename)
{
Download (remfilename,locfilename,false);
}
///
Download a remote file to a local file name which can include
A path, and set the resume flag. The local file name would be
Created or overwritten, but the path must exist.
///
///
///
///
public void Download (String remfilename,string
Locfilename,boolean resume)
{
if (!logined)
{
Login ();
}
Setbinarymode (FALSE);
Console.WriteLine ("Downloading File" +remfilename+ "from" +remotehost + "//" +remotepath);
if (Locfilename.equals (""))
{
Locfilename = Remfilename;
}
if (! File.exists (Locfilename))
{
Stream st = File.create (locfilename);
St. Close ();
}
FileStream output = new
FileStream (locfilename,filemode.create);
Socket cSocket = Createdatasocket ();
Long offset = 0;
if (resume)
{
offset = output. Length;
if (Offset > 0)
{
Setbinarymode (FALSE);
SendCommand ("REST" +offset);
if (RetValue!= 350)
{
throw new IOException (reply. Substring (4));
Some servers May is not support resuming.
offset = 0;
}
}
if (Offset > 0)
{
if (Debug)
{
Console.WriteLine ("Seeking to" + offset);
}
Long NPOs = output. Seek (Offset,seekorigin.begin);
Console.WriteLine ("New pos=" +npos);
}
}
SendCommand ("RETR" + remfilename);
if (!) ( RetValue = 150 | | RetValue = 125))
{
throw new IOException (reply. Substring (4));
}
while (true)
{
bytes = csocket.receive (buffer, buffer. Length, 0);
Output. Write (buffer,0,bytes);
if (bytes <= 0)
{
Break
}
}
Output. Close ();
if (csocket.connected)
{
Csocket.close ();
}
Console.WriteLine ("");
Readreply ();
if (!) ( RetValue = 226 | | RetValue = 250))
{
throw new IOException (reply. Substring (4));
}
}
///
Upload a file.
///
///
public void Upload (string fileName)
{
Upload (Filename,false);
}
///
Upload a file and set the resume flag.
///
///
///
public void Upload (string Filename,boolean resume)
{
if (!logined)
{
Login ();
}
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)
{
throw new IOException (reply. Substring (4));
Remote server may not support resuming.
offset = 0;
}
}
/*==========================*/
SendCommand ("STOR" +path.getfilename (fileName));
if (!) ( RetValue = 125 | | RetValue = 150))
{
throw new IOException (reply. Substring (4));
}
Open input stream to read source file
FileStream input = new FileStream (Filename,filemode.open);
if (offset!= 0)
{
if (Debug)
{
Console.WriteLine ("Seeking to" + offset);
}
Input. Seek (Offset,seekorigin.begin);
}
Console.WriteLine ("Uploading File" +filename+ "to" +remotepath);
while (bytes = input. Read (Buffer,0,buffer. Length)) > 0)
{
Csocket.send (buffer, bytes, 0);
}
Input. Close ();
Console.WriteLine ("");
if (csocket.connected)
{
Csocket.close ();
}
Readreply ();
if (!) ( RetValue = 226 | | RetValue = 250))
{
throw new IOException (reply. Substring (4));
}
}
///
Delete a file from the remote FTP server.
///
///
public void Deleteremotefile (string fileName)
{
if (!logined)
{
Login ();
}
SendCommand ("DELE" +filename);
if (RetValue!= 250)
{
throw new IOException (reply. Substring (4));
}
}
///
Rename a file on the remote FTP server.
///
///
///
public void Renameremotefile (string oldfilename,string
NewFileName)
{
if (!logined)
{
Login ();
}
SendCommand ("RNFR" +oldfilename);
if (RetValue!= 350)
{
throw new IOException (reply. Substring (4));
}
Known problem
Rnto won't take care of existing file.
i.e. It would overwrite if newfilename exist
SendCommand ("Rnto" +newfilename);
if (RetValue!= 250)
{
throw new IOException (reply. Substring (4));
}
}
///
Create a directory on the remote FTP server.
///
///
public void mkdir (string dirname)
{
if (!logined)
{
Login ();
}
SendCommand ("MKD" +dirname);
if (RetValue!= 250)
{
throw new IOException (reply. Substring (4));
}
}
///
Delete a directory on the remote FTP server.
///
///
public void RmDir (string dirname)
{
if (!logined)
{
Login ();
}
SendCommand ("RMD" +dirname);
if (RetValue!= 250)
{
throw new IOException (reply. Substring (4));
}
}
///
Change the "Current working directory" on the remote FTP server.
///
///
public void ChDir (string dirname)
{
if (Dirname.equals ("."))
{
Return
}
if (!logined)
{
Login ();
}
SendCommand ("CWD" +dirname);
if (RetValue!= 250)
{
throw new IOException (reply. Substring (4));
}
This.remotepath = dirname;
Console.WriteLine ("Current directory is" +remotepath);
}
///
Close the FTP connection.
///
public void Close ()
{
if (clientsocket!= null)
{
SendCommand ("QUIT");
}
Cleanup ();
Console.WriteLine ("Closing ...");
}
///
Set debug mode.
///
///
public void Setdebug (Boolean debug)
{
This.debug = Debug;
}
private void Readreply ()
{
Mes = "";
Reply = ReadLine ();
RetValue = Int32.Parse (reply. Substring (0,3));
}
private void Cleanup ()
{
if (clientsocket!=null)
{
Clientsocket.close ();
Clientsocket = null;
}
logined = false;
}
private String ReadLine ()
{
while (true)
{
bytes = clientsocket.receive (buffer, buffer. Length, 0);
Mes + + ASCII. GetString (buffer, 0, bytes);
if (bytes < buffer. Length)
{
Break
}
}
Char[] seperator = {' \ n '};
String[] mess = mes. Split (Seperator);
if (MES). Length > 2)
{
Mes = mess[mess. LENGTH-2];
}
Else
{
mes = mess[0];
}
if (!mes. Substring (3,1). Equals (""))
{
return ReadLine ();
}
if (Debug)
{
for (int k=0;k < mess. length-1;k++)
{
Console.WriteLine (Mess[k]);
}
}
return mes;
}
private void SendCommand (String command)
{
byte[] Cmdbytes =
Encoding.ASCII.GetBytes (command+ "\ r \ n"). ToCharArray ());
Clientsocket.send (cmdbytes, cmdbytes.length, 0);
Readreply ();
}
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);
S.setsocketoption (Socketoptionlevel.socket, Socketoptionname.sendtimeout, 5000);
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;
}
}
}